Search code examples
rmean

Element-wise mean in R


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.


Solution

  • how about:

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

    or

    colMeans(rbind(a, b), na.rm=TRUE)