Reputation: 1462
In R, I have a multidimensional list. I can access elements like:
results[["A1"]][["B2"]][["C1"]]
Of course, the output of the above statement is also a list.
What I'd like to do is something like:
results[["A1"]][[*]][["C1"]]
or
results[["A1"]][[,]][["C1"]]
My desired output would be one big list, which is the concatenation of the lists for each value (e.g., "B1", "B2", ...) in the second dimension.
Is something like this possible? I know that I can iterate over the desired dimension:
for (i in 1:length(results[["A1"]])){
output = c(output, results[["A1"]][[i]][["C1"]]
}
but I was wondering if there's anything cleaner? Am I doing it all wrong?
Upvotes: 0
Views: 752
Reputation: 263451
Does this work?
sapply( sapply(results[["A1]], "[[", TRUE), "[[", "C1"")
The generalization to a fourth level for a specific index name "D" would just be:
sapply( sapply( sapply(results[["A1"]], "[[", TRUE), "[[", "C1"), "[[", "D")
Reading from the inside out, as one needs to do with nested function calls, all of sublists of the results$A1
values are collected and then processed to construct a list of only those with "C1" names, and then that reduced list is further extracted from to yield values of the form results$A1$all-wildcards$C1$D
. Given the fact that the "[[" function will evaluate its argument you could have offer an unquoted object that had multiple values if they were valid list names at the appropriate level of indexing.
Upvotes: 1