I have a list with lists as entries, like so:
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)
I can get the elements scores1 as follows:
a1 <- lapply(ABC, "[", "scores1")
which gives me
[[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"
Now, what I really want is what is in the objects “a”, so I am looking for a call that gives me
"a"
"aa"
"aaa"
I can do this in a loop, but that seems quite inefficient. How can I extract those values? I have tried
lapply(lapply(ABC, "[", "scores1"), "[", "a")
but that only returns
[[1]]
[[1]]$<NA>
NULL
[[2]]
[[2]]$<NA>
NULL
[[3]]
[[3]]$<NA>
NULL
What is the correct way to do this?
I think you are getting tripped up by the difference between “[” and “[[“. Using “[[” gives you the contents of the elements indexed by “scores1” rather than the sublists. You can then access the contents of the elements named “a”: