s-news
[Top] [All Lists]

matrix average by element

To: s-news@lists.biostat.wustl.edu
Subject: matrix average by element
From: "Robert M. Key" <key@Princeton.EDU>
Date: Mon, 19 May 2003 09:20:38 -0400
Organization: AOS Program, Princeton Univ.
Thanks to all who responded with suggestions regarding my question
of averaging matrices by element when some of the elements were
NA. The solutions fell into 3 categories:

1. replace NA with zero then proceed. This won't work in my
situation since zero is a possible element value.
2. stack the matrices and use rowMean. This would be ideal if
3.4 had rowMean. Perhaps it's time I finally bite the bullet
and start using my newer version of S.
3. various versions of using "apply", either in 1 or 2 dimensions.
Of these solutions, Bill Venables solution was most elegantly
stated, i.e.:

Mmean <- function(...) {
        mats <- list(...)
        A <- array(unlist(mats), dim = c(dim(mats[[1]]), length(mats)))
        apply(A, c(1,2), mean, na.rm = T)
}

This hides the loops under apply, but it can't be any slower than
explicit for loops. 

I didn't mention in my note, but the number of 
matrices to be averaged will always be small <10 and the maximum matrix
dimension in this application is 180x360 with the norm being 1/3 to 1/2
that size. The application is splicing together "objective" maps of
oceanographic properties on depth or density surfaces. Unfortunately,
my CPU isn't even close to being fast enough to map properties globally
and the overhead of using the available supercomputer makes that
solution
impractical.

thanks again,
bob

<Prev in Thread] Current Thread [Next in Thread>