Element-wise mean in R
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
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?
how about:
rowMeans(cbind(a, b), na.rm=TRUE)
or
colMeans(rbind(a, b), na.rm=TRUE)