问题
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.
回答1:
how about:
rowMeans(cbind(a, b), na.rm=TRUE)
or
colMeans(rbind(a, b), na.rm=TRUE)
回答2:
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?
回答3:
A tidyverse
solution usign purrr
:
library(purrr)
a <- c(1, 2, 3, 4)
b <- c(NA, 6, 7, 8)
# expected:
c(1, 4, 5, 6)
#> [1] 1 4 5 6
# actual:
map2_dbl(a,b, ~mean(c(.x,.y), na.rm=T)) # actual
#> [1] 1 4 5 6
And for any number of vectors:
> pmap_dbl(list(a,b, a, b), compose(partial(mean, na.rm = T), c))
[1] 1 4 5 6
来源:https://stackoverflow.com/questions/3497464/element-wise-mean-in-r