[R] how to calculate means of matrix elements

Chris Stubben stubben at lanl.gov
Tue May 19 06:12:34 CEST 2009

dxc13 wrote:
>   If these three matrices are given in separate text files, how can I
> write code that will get this result I need?

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


# 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]])

Chris Stubben

View this message in context: http://www.nabble.com/how-to-calculate-means-of-matrix-elements-tp23607694p23609472.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list