开发者

Intersection of lists in R

开发者 https://www.devze.com 2023-03-19 04:14 出处:网络
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]], ...) ?

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 li开发者_如何学运维nes?


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"


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消