以递归方式提取列表中的ists中的对象

时间:2012-06-23 02:23:37

标签: r

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

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)

我可以得到以下元素得分:

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

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

1 个答案:

答案 0 :(得分:4)

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

a1 <- lapply(ABC, "[[", "scores1")
sapply(a1, "[[", "a")
#[1] "a"   "aa"  "aaa"