我在 R 中创建了一个矩阵列表。在列表中的所有矩阵中,我想“拉出”特定索引的矩阵元素集合。我在想冒号运算符可能允许我在一行中实现它。例如,这里尝试访问列表中所有矩阵的 [1,1] 元素:
myList = list() #list of matrices
myList[[1]] = matrix(1:9, nrow=3, ncol=3, byrow=TRUE) #arbitrary data
myList[[2]] = matrix(2:10, nrow=3, ncol=3, byrow=TRUE)
#I expected the following line to output myList[[1]][1,1], myList[[2]][1,1]
slice = myList[[1:2]][1,1] #prints error: "incorrect number of dimensions"
上述代码的最后一行抛出错误“维数不正确”。
作为引用,这是我正在尝试做的工作(但不太优雅)的实现:
#assume myList has already been created (see the code snippet above)
slice = c()
for(x in 1:2) {
slice = c(slice, myList[[x]][1,1])
}
#this works. slice = [1 2]
有谁知道如何在一行中完成上述操作?
请注意,我的“矩阵列表”可以替换为其他内容。如果有人可以建议允许我执行上述操作的替代“矩阵集合”数据结构,那么这将得到解决。
也许这个问题很愚蠢……不过我真的很想有一个干净的单行实现。
最佳答案
两件事。首先,[
和[[
的区别。 ?'['
中的相关句子:
The most important distinction between [, [[ and $ is that the [ can select more than one element whereas the other two select a single element.
所以你可能想要做 myList[1:2]
。其次,您不能按照您描述的方式组合子集操作。执行 myList[1:2]
后,您将获得两个矩阵的列表。列表通常只有一维,因此 myList[1:2][1,1]
在您的情况下是没有意义的。 (请参阅异常(exception)情况的评论。)
您可以尝试使用 lapply
:lapply(myList,'[',1,1)
。
关于矩阵列表上的 R 冒号运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10526954/