Element-wise mean in R

前端 未结 3 946
感情败类
感情败类 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

    how about:

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

    or

    colMeans(rbind(a, b), na.rm=TRUE)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-11 00:42

    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?

    0 讨论(0)
提交回复
热议问题