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 another way to do it ...



names(nestedlist) <- paste0("Group",1:length(nestedlist)) #add names to list
lookup <- unlist(nestedlist) #unlist, retaining names
names(lookup)[match(test,lookup)] #lookup matching names

[1] "Group1.color1" "Group2.taste1"

      

+1


source


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







All Articles