R:将函数应用于列表矩阵的每个元素并且 return 导致相同的矩阵格式

R: apply function to each element of the matrix of lists and return result in the same matrix format

假设我有一个列表矩阵:

theList <- matrix(list(rnorm(10), rnorm(10), rnorm(10), rnorm(10)), nrow=2, ncol=2)
theList
     [,1]       [,2]
[1,] Numeric,10 Numeric,10
[2,] Numeric,10 Numeric,10

我想对这个矩阵的每个元素应用一些函数,同时保留原始尺寸。

我发现以下内容适用于 sapply:

apply(theList, 2, sapply, mean)
           [,1]      [,2]
[1,]  0.5678905 0.0577225
[2,] -0.2708252 0.5045110

但是它不适用于 lapply:

apply(theList, 2, lapply, mean)
[[1]]
[[1]][[1]]
[1] 0.5678905

[[1]][[2]]
[1] -0.2708252


[[2]]
[[2]][[1]]
[1] 0.0577225

[[2]][[2]]
[1] 0.504511

如何将函数应用于列表矩阵中的每个列表和return相同格式的数据 - 具有相同维度的列表矩阵?

从向量或列表重建矩阵的成本并不高,因为它只设置了对象的 dim 属性。所以我会这样做:

res <- matrix(lapply(theList,mean),nrow(theList));
res;
##      [,1]       [,2]
## [1,] -0.1956084 0.03062223
## [2,] -0.2106935 0.1842444

请注意,虽然上面的结果显示得非常像一个双精度矩阵,但它实际上仍然是一个列表矩阵:

str(res);
## List of 4
##  $ : num -0.196
##  $ : num -0.211
##  $ : num 0.0306
##  $ : num 0.184
##  - attr(*, "dim")= int [1:2] 2 2

plyr 中的这种方法似乎有效:

library(plyr)
llply(theList, range)
         [,1]      [,2]
[1,] Numeric,2 Numeric,2
[2,] Numeric,2 Numeric,2

这个呢,purrr中有很多函数可以像你这样的映射函数,

library(purrr)
apply(theList, 2, map_dbl, mean)