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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to