在R中获取嵌套列表的列表和列表元素名称

3

我制作了一个与下面类似的嵌套列表。

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)

现在从这个“嵌套列表”中,我想找出一个元素属于哪个组以及它属于哪个列表元素。请原谅我对列表结构的理解不足。
例如:
test <- c("red", "tan")

给定一个测试,我想要返回"color" "group1"和"taste" "group2"的结果。

是否有任何函数可以做到这一点?我经常在列表方面遇到困难。任何帮助都将不胜感激。


1
你尝试过使用 nestedlist <- list(g1 = group1, g2 = group2) 而不是 nestedlist <- list(group1, group2) 吗?这样,你可以直接对 unlist(nestedlist) 进行搜索。 - Aramis7d
关于名称的观点很有道理,但是当你有类似 nestedlist <- list(g2.g1 = group1, g2 = group2) 的嵌套列表时,情况可能会变得困难。 - thelatemail
2个回答

2

这里是一种可能的解决方案:

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))]])))}))

输出:

     group col     
[1,] "1"   "color" 
[2,] "2"   "taste"

如果一个组比另一个组有更多的嵌套列表,它也可以工作,这是我最初遇到的问题。好奇地看到其他人的解决方案,希望这可以帮助!


我遇到了以下错误:Error in x[[which(sapply(x, any))]] : attempt to select more than one element in vectorIndex - duvvurum

2
这里是另一种做法...
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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接