tags:

views:

72

answers:

2

In R, I have two vectors:

a <- c(1, 2, 3, 4)
b <- c(NA, 6, 7, 8)

How do I find the element-wise mean of the two vectors, removing NA, without a loop? i.e. I want to get the vector of

(1, 4, 5, 6)

I know the function mean(), I know the argument na.rm = 1. But I don't know how to put things together. To be sure, in reality I have thousands of vectors with NA appearing at various places, so any dimension-dependent solution wouldn't work. Thanks.

+5  A: 

how about:

rowMeans(cbind(a, b), na.rm=TRUE)

or

colMeans(rbind(a, b), na.rm=TRUE)
Greg
Ok, those are cool. But to get what I wanted you still need to add `na.rm = 1`, and that solves my problem. Thx.
Zhang18
I just added the na.rm arguments.
Greg
`colSums` and `rowSums` also exist @Zhang18, FYI.
Vince
Thanks for the info, Vince.
Zhang18
+1  A: 

I'm not exactly sure what you are asking for, but does

apply(rbind(a,b),2,mean,na.rm = TRUE)

do what you want?

deinst
Yes, this works too. thx.
Zhang18
The Details section of ?colMeans and ?rowMeans explains that these functions are much faster than apply with fun = mean as they are implemented for speed.
Greg