Skip to content

how to calculate means of matrix elements

6 messages · jim holtman, Chris Stubben, dxc13 +1 more

#
useR's,
I have several matrices of size 4x4 that I want to calculate means of their
respective positions with.  For example, consider I have 3 matrices given by
the code:
mat1 <- matrix(sample(1:20,16,replace=T),4,4)
mat2 <- matrix(sample(-5:15,16,replace=T),4,4)
mat3 <- matrix(sample(5:25,16,replace=T),4,4)

The result I want is one matrix of size 4x4 in which position [1,1] is the
mean of position [1,1] of the given three matrices.  The same goes for all
other positions of the matrix.  If these three matrices are given in
separate text files, how can I write code that will get this result I need?

Thanks in advance,
dxc13
#
Try this:

(mat1 + mat2 + mat3) / 3
On Mon, May 18, 2009 at 8:40 PM, dxc13 <dxc13 at health.state.ny.us> wrote:
#
dxc13 wrote:
If you have matrices in separate text files like mat1.txt, mat2.txt,
mat3.txt, you could load them into a list using a loop

x<- vector('list', 3)

for ( i in 1:3)
{
   ## you may to change some default options for read.table
   x[[i]]<-as.matrix(read.table(paste( 'mat', i, '.txt', sep='')))
}

Then write a function to calculate the mean of a list of matrices

mean(x)


# Paste this function into R before running mean(x) ? its also included in
the popbio package

mean.list<-function (x, ...) 
{
    if (!all(sapply(x, is.matrix))) 
        stop("'x' must be a list containing matrices")
    dims <- sapply(x, dim)
    n <- dims[1, 1]
    p <- dims[2, 1]
    if (!all(n == dims[1, ]) || !all(p == dims[2, ])) 
        stop("the matrices must have the same dimensions")
    mat <- matrix(unlist(x), n * p, length(x))
    mm <- matrix(rowMeans(mat, ...), n, p)
    dimnames(mm) <- dimnames(x[[1]])
    mm
}


Chris Stubben
#
Easy enough.  What if some of the matrix elements contained missing values? 
Then how could you still calculate the means?  Example code below:
mat1 <- matrix(c(1,2,3,4,5,NA,7,8,9),3,3)
mat2 <- matrix(c(NA,6,1,9,0,5,8,2,7),3,3)
mat3 <- matrix(c(5,9,1,8,NA,3,7,2,4),3,3)
Gabor Grothendieck wrote:

  
    
#
In that case use a modification of Jim's solution:

a <- array(cbind(mat1, mat2, mat3), c(3, 3, 3))
apply(a, 1:2, mean, na.rm = TRUE)
On Tue, May 19, 2009 at 8:49 AM, dxc13 <dxc13 at health.state.ny.us> wrote: