Getting list and list of list items for nested list in R
I made a nested list like the one below.
group1 <- list(color = c("red", "green", "blue"),taste = c("sweet", "sour"))
group2 <- list(color = c("orange","purple","yellow"),taste = c("tan", "salt"))
nestedlist <- list(group1, group2)
now from this "nested list", I want to know which group an item belongs to, and which list item it belongs to. Forgive my lack of understanding with the structure of the list.
for example
test <- c("red", "tan")
for this test I want to return "color" "group1" and "taste" "group2" ..
Is there any function for this? I struggle with lists a lot. any help would be appreciated
+3
source to share
2 answers
Here's a possible solution:
dat = lapply(test,function(z){sapply(nestedlist,function(x)
{sapply(x,function(y) {z %in% y})})})
do.call(rbind,lapply(dat, function(x) {c(group = which(sapply(x,any)),
col = names(which(x[[which(sapply(x,any))]])))}))
Output:
group col
[1,] "1" "color"
[2,] "2" "taste"
It also works if one group has more nested lists than the other, which I was struggling with initially. Curious to see others' solution, hope this helps!
+2
source to share