对这个简单的问题很抱歉,但是我想不出一种获取数据帧列表中的函数元素的好方法。我敢肯定plyr/reshape2软件包中有某些东西,但我只是想不到。

例如,我有一个列表A,如下所示:

>A
[[1]]
        [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
   [1,]    1    1    1    1    1    1    1    1    1     1
   [2,]    1    1    1    1    1    1    1    1    1     1
   [3,]    1    1    1    1    1    1    1    1    1     1
   [4,]    1    1    1    1    1    1    1    1    1     1
   [5,]    1    1    1    1    1    1    1    1    1     1

[[2]]
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    2    2    2    2    2    2    2    2    2     2
 [2,]    2    2    2    2    2    2    2    2    2     2
 [3,]    2    2    2    2    2    2    2    2    2     2
 [4,]    2    2    2    2    2    2    2    2    2     2
 [5,]    2    2    2    2    2    2    2    2    2     2

假设我想对列表中矩阵的相应元素取均值。一种方法是
Reduce("+",A)/length(A)

我似乎无法提供Reduce()更复杂的功能,并假设总体上没有更好的方法。

最佳答案

在这种情况下,也许您最好将数据放在array中而不是列表中?

#Recreate data
A <- list(a=matrix(1,5,10),b=matrix(2,5,10))

#Convert to array
A1 <- array(do.call(cbind,A),dim = c(5,10,2))

#Better way to convert to array
require(abind)
A1 <- abind(A,along = 3)

#Now we can simply use apply
apply(A1,c(1,2),mean)

关于r - 将功能应用于列表中的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7085110/

10-12 00:09
查看更多