【问题标题】:How to save the structure of my list of matrices from lapply-attack?如何从 lapply-attack 中保存我的矩阵列表的结构?
【发布时间】:2014-06-11 05:25:59
【问题描述】:

我想将整数矩阵列表转换为数字。我知道 lapply 对内部结构不友好,但是有 lapply 的解决方案吗?

mtList = list(matrix(sample(1:10),nrow=5),
              matrix(sample(1:21),nrow=7))
str(mtList)

# This works, and I could wrap it in a for loop
mtList[[1]][] = as.numeric(mtList[[1]])
mtList[[2]][] = as.numeric(mtList[[2]])
str(mtList)

# But how to use lapply here? Note that the internal
# matrix structure is flattened
mtList1 = lapply(mtList,function(x)x[] = as.numeric(x))
str(mtList1)

【问题讨论】:

  • +1。我以前从未想过这种行为。
  • 我也是。我刚刚通过阅读这个问题学到了很多东西。有趣的东西。
  • +.5 表示好问题 +.5 表示好标题 :)
  • 嗯,标题被证明是错误的......是索引,而不是 lapply,刺穿......

标签: r list matrix


【解决方案1】:

您必须在 lapply 主力函数中返回值:

mtList1 = lapply(mtList,function(x) {
  x[] = as.numeric(x)
  x
})

str(mtList1)
# List of 2
#  $ : num [1:5, 1:2] 1 7 6 3 9 10 5 2 8 4
#  $ : num [1:7, 1:3] 21 3 15 14 6 4 18 17 9 8 ...

【讨论】:

  • 谢谢。我隐式返回了 x[],这是罪魁祸首
【解决方案2】:

一个稍微简单的替代方法可能是通过乘以 1.0 来强制(或者可以说,更稳健,提高到 1.0 的幂)...

mtList1 <- lapply( mtList , "*" , 1.0 )
str(mtList1)
#List of 2
# $ x: num [1:5, 1:2] 2 8 1 5 7 9 3 10 4 6
# $ x: num [1:7, 1:3] 17 20 9 11 2 18 1 4 12 10 ...

【讨论】:

  • 你是对的特殊情况,但我用它 as.numeric 作为一个更复杂过程的例子
  • @DieterMenne 另一种选择是x^1.0。 AFAIK 这保留了NAInfNaN
猜你喜欢
  • 2017-05-09
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
  • 2023-01-02
  • 1970-01-01
  • 2021-11-13
相关资源
最近更新 更多