Intersection of lists in R

别说谁变了你拦得住时间么 提交于 2020-12-01 09:14:27

问题


Is there a function that receives a list x and returns a list y such that y[[i]] = intersect(x[[1]][[i]], x[[2]][[i]], ...) ?

If not, is there a R way to code it in a couple of lines?


回答1:


Does this work?

x <- list(list(1:3,2:4),list(2:3,4:5),list(3:7,4:5))
maxlen <- max(sapply(x,length))
lapply(seq(maxlen),function(i) Reduce(intersect,lapply(x,"[[",i)))

(intersect only takes two arguments so you have to use Reduce as an additional step)

PS I haven't tried this on any hard cases -- e.g. lists of uneven length.




回答2:


It seems the Reduce can be simply used as follows:

> Reduce(intersect,  list(v1 = c("a","b","c","d"), 
+                         v2 = c("a","b","e"), 
+                         v3 = c("a","f","g"))) 
[1] "a"


来源:https://stackoverflow.com/questions/6630792/intersection-of-lists-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!