[R] matrix elementwise average with NA's

Marc Schwartz marc_schwartz at comcast.net
Wed Nov 21 21:14:32 CET 2007


On Wed, 2007-11-21 at 14:30 -0500, Gregory Gentlemen wrote:
> Hello fellow R users,
> 
> I have a matrix computation that I imagine should be relatively easy
> to do, however I cannot figure out a nice way to do it. I have two
> matrices, for example
> 
> mat1 <- matrix(c(1:5,rep(NA,5), 6:10), nrow=3, byrow=T)
> mat2 <- matrix(c(2:6, 6:10, rep(NA,5)), nrow=3, byrow=T)
> 
> I'd like to compute the element-wise average for non-NA entries. Of
> course
> 
> (mat1+mat2)/2
> 
> does not work for the final two rows because of the NA's. Are there
> any elegant ways to accopmlish this without writing a loop with
> indices?
> 
> Thanks in advance for any assistance.
> 
> Greg

Is this what you want?

> matrix(colMeans(rbind(as.vector(mat1), as.vector(mat2)), 
         na.rm = TRUE), dim(mat1))
     [,1] [,2] [,3] [,4] [,5]
[1,]  1.5  2.5  3.5  4.5  5.5
[2,]  6.0  7.0  8.0  9.0 10.0
[3,]  6.0  7.0  8.0  9.0 10.0

?

HTH,

Marc Schwartz



More information about the R-help mailing list