Maas James Dr (MED)
2011-Oct-09 17:04 UTC
[R] apply to a matrix and insert in the middle of an array
If possible I'd like to produce a function that applies a formula to a column in a matrix (essentially calculating the mse) and then inserts it between values of a an array ... confusing I know, here is an example of what I'm trying to accomplish: ## create a matrix (a <- matrix(c(3,6,4,8,5,9,12,15),nrow=4)) ## get the mean of all columns (b <- apply(a,2,mean)) ## calculate the mse of column 1 (c <- (sd(a[,1])/sqrt(length(a[,1])))) ## calculate the mse of column 2 (d <- (sd(a[,2])/sqrt(length(a[,2])))) ## now create a new vector with each mean value and its corresponding ## mse right beside it (e <- c(b[1],c,b[2],d)) Would anyone have any suggestions how to accomplish this using an apply statement? Thanks a bunch, J ==============================Dr. Jim Maas University of East Anglia
David Winsemius
2011-Oct-09 17:57 UTC
[R] apply to a matrix and insert in the middle of an array
On Oct 9, 2011, at 1:04 PM, Maas James Dr (MED) wrote:> If possible I'd like to produce a function that applies a formula to > a column in a matrix (essentially calculating the mse) and then > inserts it between values of a an array ... > > confusing I know, here is an example of what I'm trying to accomplish: > > ## create a matrix > (a <- matrix(c(3,6,4,8,5,9,12,15),nrow=4)) > ## get the mean of all columns > (b <- apply(a,2,mean)) > ## calculate the mse of column 1 > (c <- (sd(a[,1])/sqrt(length(a[,1])))) > ## calculate the mse of column 2 > (d <- (sd(a[,2])/sqrt(length(a[,2]))))The sd function, like the var function, returns its values based on columns, so just sd(a) fives you a vector of columns. Construting an interleaving vector of column indices can be done matrix manipulations: c(b, sd(a))[ c( matrix(1:(2*length(b)), 2, byrow=TRUE) # create a row-oriented matrix ) # the interleaving matrix is then extracted as a vector by columns ] #[1] 5.250000 2.217356 10.250000 4.272002 ( You could also use the apply method of returning function(x) { c(mean(x), sd(x) } from each column.) and then wrap the c() function around that: c( apply(a, 2, function(x){ c(mean(x), sd(x) ) }) ) #[1] 5.250000 2.217356 10.250000 4.272002> ## now create a new vector with each mean value and its corresponding > ## mse right beside it > (e <- c(b[1],c,b[2],d)) > > Would anyone have any suggestions how to accomplish this using an > apply statement? > > Thanks a bunch, > > J > ==============================> Dr. Jim Maas > University of East AngliaDavid Winsemius, MD West Hartford, CT