One way is to bind the matrices into a 3d array and use either apply() or
rowMeans(), both with arguments na.rm=T. The library abind in statlib
(http://lib.stat.cmu.edu/S/abind) does the binding, and rowMeans should be
faster than apply.
> rowMeans(abind(A,B,C,along=3),na.rm=T,dims=2) # one way
> apply(abind(A,B,C,along=3),1:2,mean,na.rm=T) # another way
Nick Ellis
CSIRO Marine Research mailto:Nick.Ellis@csiro.au
PO Box 120 ph +61 (07) 3826 7260
Cleveland QLD 4163 fax +61 (07) 3826 7222
Australia http://www.marine.csiro.au
> -----Original Message-----
> From: Robert M. Key [mailto:key@Princeton.EDU]
> Sent: Saturday, 17 May 2003 3:27 AM
> To: s-news@lists.biostat.wustl.edu
> Subject: [S] matrix average by element
>
>
> S-Plus 3.4 on Solaris 5.8
>
> I'm trying to calculate an element by element average on equal
> dimensioned matrices (say A,B,C). Normally I could just say
> junk_(A+B+C)/3
>
> The problem is that many of the matrix elements are NA and the
> distribution of the NAs differs from one matrix to the next.
> If any of the i,j elements is not NA, then I want a value.
>
> For example
> A[i,j]=1
> B[i,j]=2
> C[i,j]=NA
> I want junk[i,j] to have (1+2)/2
> If only one of the matrices has a non-NA value then I want junk[i,j]
> to have that one value.
>
> The brute force double loop solution naturally works, but it is
> slow due to the number of required iterations.
>
> There must be an efficient solution, but I haven't been able to
> find it. Suggestions would be appreciated.
>
> thx,
> bob
> --------------------------------------------------------------------
> This message was distributed by s-news@lists.biostat.wustl.edu. To
> unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
> the BODY of the message: unsubscribe s-news
>
|