3

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 find out the which group an element belongs and which list element it belongs. Pardon my lack of understanding with list structure.

For example

test <- c("red", "tan")

given test i want the return of "color" "group1" and "taste" "group2"..

Is there any function to do this? I struggle with lists often. any help would be appreciated

2
  • 1
    have you tried nestedlist <- list(g1 = group1, g2 = group2) instead of nestedlist <- list(group1, group2) ? This way, you can just do unlist(nestedlist) and search on that. Commented Aug 2, 2017 at 5:32
  • Fair point about the names, but it can become difficult when you have nestedlist <- list(g2.g1 = group1, g2 = group2) for instance. Commented Aug 2, 2017 at 5:43

2 Answers 2

2

Here is 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"
Sign up to request clarification or add additional context in comments.

Comments

2

Here is 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 was what I struggled with initially. Curious to see the solution of others, hope this helps!

1 Comment

I am getting below error: Error in x[[which(sapply(x, any))]] : attempt to select more than one element in vectorIndex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.