R 中列表对应元素的均值(或其他函数)

Mean(or other function) of corresponding elements of a list in R

我有一个列表,这个列表中的每个元素都是一个向量并且具有相同的长度。我想计算每个向量的所有第一个元素的平均值(或其他值,它可以是用户定义的函数),每个向量的所有第二个元素的平均值(或其他值,它可以是用户定义的函数)等。和 return 一个向量。所以这与问题 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()
}

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

colMeans(do.call(rbind, list1))

[1] 2 3 4 5 6

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

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