s-news
[Top] [All Lists]

Re: matrix average by element

To: "Robert M. Key" <key@Princeton.EDU>
Subject: Re: matrix average by element
From: John Fox <jfox@mcmaster.ca>
Date: Mon, 19 May 2003 09:32:34 -0400
Cc: s-news@lists.biostat.wustl.edu
In-reply-to: <3EC8DA26.87450208@princeton.edu>
Dear Bob,

At 09:20 AM 5/19/2003 -0400, Robert M. Key wrote:
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.

The other solutions are nicer, but putting in zeroes does work, even if there are legitimate zeroes, since zeroes do not increase the sum, while the denominator is based on the number of non-NA entries.

Regards,
 John

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.

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox@mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------


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