如何从lapply攻击中保存矩阵列表的结构?

3
我想将一个整数矩阵列表转换为数字类型。我知道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. 我以前从未考虑过这种行为。 - Simon O'Hanlon
我也是。读了这个问题后,我学到了很多东西。非常有趣的内容。 - Rich Scriven
+.5 为了一个好问题 +.5 更多为了一个好标题 :) - Tyler Rinker
标题证明是错误的... 是索引而不是lapply刺破了... - Dieter Menne
2个回答

4
你需要在你的 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[],这就是罪魁祸首。 - Dieter Menne

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作为更复杂过程的示例。 - Dieter Menne
@DieterMenne 另一个选择是 x^1.0。据我所知,这可以保留 NAInfNaN - Simon O'Hanlon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接