【问题标题】:Calculate means across elements in a list计算列表中元素的平均值
【发布时间】:2019-03-18 20:01:51
【问题描述】:

我有一个这样的list

(mylist <- list(a = data.frame(x = c(1, 2), y = c(3, 4)),
                b = data.frame(x = c(2, 3), y = c(4, NA)),
                c = data.frame(x = c(3, 4), y = c(NA, NA))))
$a
  x y
1 1 3
2 2 4

$b
  x  y
1 2  4
2 3 NA

$c
  x  y
1 3 NA
2 4 NA

purrr::map() 创建。如何计算相应单元格中值的平均值?即

  x   y
1 2 3.5
2 3   4

在哪里

mean(c(1,  2,  3), na.rm = T) # = 2
mean(c(2,  3,  4), na.rm = T) # = 3
mean(c(3,  4, NA), na.rm = T) # = 3.5
mean(c(4, NA, NA), na.rm = T) # = 4

感谢您的帮助!

【问题讨论】:

    标签: r list aggregate purrr


    【解决方案1】:

    一种方法是将列表转换为数组,然后在数组的第三维上应用均值函数:

    my_array <- array(unlist(mylist), dim=c(2,2,3))
    apply(my_array, c(1,2), mean, na.rm=T)
    
    #      [,1] [,2]
    # [1,]    2  3.5
    # [2,]    3  4.0
    

    如果您想一次性完成所有这些操作,而无需对尺寸进行硬编码,您可以这样做:

    apply(array(unlist(mylist), dim=c(nrow(mylist[[1]]),ncol(mylist[[1]]),length(mylist))), c(1,2), mean, na.rm=T)
    

    【讨论】:

      【解决方案2】:

      purrr 选项

      library(purrr)
      map_df(transpose(mylist), ~rowMeans(as.data.frame(.x), na.rm = TRUE))
       # A tibble: 2 x 2
      #      x     y
      #  <dbl> <dbl>
      #1     2   3.5
      #2     3   4  
      

      【讨论】:

        【解决方案3】:
        Reduce(function(x, y) x + replace(y, is.na(y), 0), mylist)/
            Reduce(`+`, lapply(mylist, function(x) !is.na(x)))
        #  x   y
        #1 2 3.5
        #2 3 4.0
        

        nm = c("x", "y")  # could do `nm = names(mylist[[1]])`
        sapply(nm, function(NM)
            rowMeans(do.call(cbind, lapply(mylist, function(x) x[NM])), na.rm = TRUE))
        #     x   y
        #[1,] 2 3.5
        #[2,] 3 4.0
        

        【讨论】:

          猜你喜欢
          • 2018-03-19
          • 2018-06-21
          • 2013-06-07
          • 1970-01-01
          • 1970-01-01
          • 2018-02-18
          • 1970-01-01
          • 2023-03-24
          • 1970-01-01
          相关资源
          最近更新 更多