我有一个包含 100 个元素的列表。每个元素都是一个列表。这个列表中有两个元素。一个只是键,另一个是矩阵。这个矩阵有 5 列。我正在尝试从每个矩阵中为所有元素提取一列。所以基本上我会再次将 100 个矩阵作为列表的一个元素。这是列表的样子
a[[1]]
[[1]]
[1] "keyid"
[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] "1329397986.572332" "x" "y" "z" "a"
[2,] "1329242747.368294" "x" "y" "z" "a"
[3,] "1329194224.351232 "x" "y" "z" "a"
所以你在这里看到的是一个列表,它有 100 个元素。每个元素都是 2 个元素的列表。我目前只对第二个元素感兴趣。第二个元素有一个矩阵。我想提取这个矩阵的第一列。只是想看看我是否可以将列提取到我可以做的向量中
a[[1]][[2]][,1]
我将所有值作为向量获取,如下所示。
a[[1]][[2]][,1]
[1] "1329397986.572332" "1329242747.368294" "1329194224.351232"
但是当我这样做时
x <- lapply(a,function(r){r[[2]][,1]})
以下是我得到的错误。
> x <- lapply(a, function(r){r[[2]][,1]})
Error in r[[2]][, 1] : incorrect number of dimensions
我不确定我为什么会这样。我检查了矩阵元素的尺寸。
> dim(a[[1]][[2]])
[1] 52 5
它看起来是正确的。所以我不确定错误在哪里。
dput(a) 给出
dput(a)
[[1]]
[[1]][[1]]
[1] "keyid"
[[1]][[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] "1329397986.572332" "x" "y" "z" "a"
[2,] "1329242747.368294" "x" "y" "z" "a"
[3,] "1329194224.351232" "x" "y" "z" "a"
[[2]]
[[2]][[1]]
[1] "keyid"
[[2]][[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] "1329397986.572332" "x" "y" "z" "a"
[2,] "1329242747.368294" "x" "y" "z" "a"
[3,] "1329194224.351232" "x" "y" "z" "a"
...
[[100]]
[[100]][[1]]
[1] "keyid"
[[100]][[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] "1329397986.572332" "x" "y" "z" "a"
[2,] "1329242747.368294" "x" "y" "z" "a"
[3,] "1329194224.351232" "x" "y" "z" "a"