3

我有一个列表作为条目,如下所示:

A <- list(scores1 = list(a = "a", b = "b"), scores2 = list(a = "c", b = "d"), scores3 = list(a = "e", b = "f"))
B <- list(scores1 = list(a = "aa", b = "bb"), scores2 = list(a = "cc", b = "dd"), scores3 = list(a = "ee", b = "ff"))
C <- list(scores1 = list(a = "aaa", b = "bbb"), scores2 = list(a = "ccc", b = "ddd"), scores3 = list(a = "eee", b = "fff"))
ABC <- list(A, B, C)

我可以得到元素 score1 如下:

a1 <- lapply(ABC, "[", "scores1")

这给了我

[[1]]
[[1]]$scores1
[[1]]$scores1$a
[1] "a"

[[1]]$scores1$b
[1] "b"

[[2]]
[[2]]$scores1
[[2]]$scores1$a
[1] "aa"

[[2]]$scores1$b
[1] "bb"

[[3]]
[[3]]$scores1
[[3]]$scores1$a
[1] "aaa"

[[3]]$scores1$b
[1] "bbb"

现在,我真正想要的是对象“a”中的内容,所以我正在寻找一个给我的电话

"a"
"aa"
"aaa"

我可以循环执行此操作,但这似乎效率很低。如何提取这些值?我努力了

lapply(lapply(ABC, "[", "scores1"), "[", "a")

但这只会返回

[[1]]
[[1]]$<NA>
NULL

[[2]]
[[2]]$<NA>
NULL

[[3]]
[[3]]$<NA>
NULL

这样做的正确方法是什么?

4

1 回答 1

4

我认为你被“[”和“[[”之间的区别绊倒了。使用“[[”为您提供由“scores1”索引的元素的内容,而不是子列表。然后,您可以访问名为“a”的元素的内容:

a1 <- lapply(ABC, "[[", "scores1")
sapply(a1, "[[", "a")
#[1] "a"   "aa"  "aaa"
于 2012-06-23T02:37:19.123 回答