Element-wise mean in R

前端 未结 3 950
感情败类
感情败类 2020-12-10 23:42

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,

3条回答
  •  既然无缘
    2020-12-11 00:33

    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
    

提交回复
热议问题