gpt4 book ai didi

递归提取列表中 ists 中的对象

转载 作者:行者123 更新时间:2023-12-01 12:52:56 27 4
gpt4 key购买 nike

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

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)

我可以得到元素 scores1 如下:

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

正确的做法是什么?

最佳答案

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

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

关于递归提取列表中 ists 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11166289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com