[R] apply to a matrix and insert in the middle of an array

David Winsemius dwinsemius at comcast.net
Sun Oct 9 19:57:44 CEST 2011


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 Anglia

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list