问题
In R, I have a list, composed of 12 sublists, each themselves composed of 5 subsublists as follow
lists and sublists
In this example, I want to extract the info "MSD", for each of these sublists.
I can extract the level "statistics" for each using
lapply(letters, '[[', "statistics")
That worked well. It gave me all the values contained in the sublist "statistics", for each list However, I want to go one level down of that, as I am not interested in the other data such as MSerror, Df, ..... Only MSD
I tried
lapply(letters, '[[', "statistics", "MSD")
and many others without success.
If I wanted only the first sublist, it will work with
letters[[1]][["statistics"]][["MSD"]]
but then, I have to do:
letters[[1]][["statistics"]][["MSD"]]
letters[[2]][["statistics"]][["MSD"]]
letters[[3]][["statistics"]][["MSD"]]
which I want to avoid for a matter of time.
thanks for your help.
回答1:
We can use a lambda/anonymous function
lapply(letters, function(x) x[["statistics"]][["MSD"]])
The benefit of this function is that if we have multiple nested elements, we don't have to call n
lapply
and should be faster
Or use map
library(tidyverse)
map(letters, ~ .x[["statistics"]][["MSD"]])
Also, regarding the claim that this wouldn't work if there are not some elements in the list
,
set.seed(24)
lst1 <- replicate(3, list(statistics = list(MSD = rnorm(20))))
names(lst1)[2] <- "Hello"
It is true that it wouldn't work. However, it wouldn't work with the solution claimed to be work as well.
回答2:
One option is a nested lapply:
lapply(lapply(letters, '[[', "statistics"),`[[`,"MSD")
The benefit of this over @akrun's approach, which may not be relevant in this case, is that it will work even if some of the elements within the list don't have an $statistics$MSD item.
来源:https://stackoverflow.com/questions/53524769/subset-of-a-subset-of-a-list