Element-wise mean in R

倖福魔咒の 提交于 2019-11-27 06:34:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!