【问题标题】:Mean(or other function) of corresponding elements of a list in R [duplicate]R中列表的相应元素的平均值(或其他函数)[重复]
【发布时间】:2016-10-31 20:10:27
【问题描述】:

我有一个列表,这个列表中的每个元素都是一个向量并且具有相同的长度。我想计算每个向量的所有第一个元素的平均值(或其他值,它可以是用户定义的函数),每个向量的所有第二个元素的平均值(或其他值,它可以是用户定义的函数)等。并返回一个向量。所以这与问题How to sum a numeric list elements in R 不同。下面的代码给了我我想要的,但是,有没有更有效和更复杂的方法来做到这一点?谢谢。

list1 <- list(a=1:5,b=2:6,c=3:7)
result <- numeric(length(list1[[1]]))
for(i in 1:length(list1[[1]])){
  result[i] <- mean(c(list1[[1]][i],list1[[2]][i],list1[[3]][i])) #the function can be any other function rather than mean()
}

【问题讨论】:

  • 我会做library(data.table); sapply(transpose(list1), mean),但这需要一个包。也许colMeans( do.call(rbind, list1) )..?
  • 谢谢@Frank,我只是想知道是否可以在没有任何额外包的情况下完成这个?
  • Reduce("+",list1)/length(list1)
  • @paqmo 这是一个非常出色的解决方案,您应该发布它。你有我的投票。
  • 有点相关:stackoverflow.com/q/24478531 是的,我喜欢 Reduce 方式。

标签: r list apply


【解决方案1】:

这是一个使用Reduce 函数的选项:

Reduce("+",list1)/length(list1)
[1] 2 3 4 5 6

【讨论】:

    【解决方案2】:

    如何将它们全部放在一个矩阵中,然后计算列的平均值?

    colMeans(do.call(rbind, list1))
    
    [1] 2 3 4 5 6
    

    【讨论】:

      猜你喜欢
      • 2013-07-22
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 2012-11-01
      相关资源
      最近更新 更多