【问题标题】:R: apply function to each element of the matrix of lists and return result in the same matrix formatR:将函数应用于列表矩阵的每个元素并以相同的矩阵格式返回结果
【发布时间】:2016-04-09 20:35:49
【问题描述】:

假设我有一个列表矩阵:

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

如何将函数应用于列表矩阵中的每个列表,并以相同格式返回数据 - 具有相同维度的列表矩阵?

【问题讨论】:

  • 列表矩阵是一种糟糕的数据结构。另外,如果sapply() 工作正常,你为什么还要关心lapply()
  • 如果这行得通,对我来说这将是一个足够好的结构。我不想要sapply,因为它仅限于返回单个值作为输出的函数。 lapply 更加通用和一致。
  • 我想simplify2array(apply(theList, 2, lapply, mean)) 会起作用。甚至`dim&lt;-`(lapply(theList, mean), dim(theList))
  • 我同意。也不确定是否理解,但也许您想在矩阵的每个单元格中都有列表?如果是,这可以工作apply(theList, 1:2, function(x) list(sapply(x, mean)))
  • @HaddE.Nuff 是的,那些似乎工作。非常感谢。只希望它比那更简单。想知道plyr 在这里是否有任何帮助.. @VincentBonhomme - 一次通话中有两个保证金适用于什么? apply(theList, 1:2, lapply, mean) 似乎在工作,但不确定它的作用。

标签: r list matrix lapply


【解决方案1】:

从向量或列表中重建矩阵并不昂贵,因为它只在对象上设置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

【讨论】:

  • 谢谢+1。我有一种类似的方法来根据结果制作矩阵。但正在寻找一个“更优雅”的解决方案。现在发现plyrllply 似乎做得很好。但是在基础 R 中,您给出的这个答案是迄今为止最好的。
【解决方案2】:

这个呢,purrr 里面有很多函数可以映射你这种情况,

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

【讨论】:

    【解决方案3】:

    似乎plyr 的这种方法正在奏效:

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

    【讨论】:

      猜你喜欢
      • 2018-12-04
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2013-02-21
      • 2021-04-20
      • 1970-01-01
      相关资源
      最近更新 更多