Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection of lists in R

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?

like image 450
gappy Avatar asked Jul 08 '11 21:07

gappy


People also ask

How do you find the intersection in R?

intersect() function in R Language is used to find the intersection of two Objects. This function takes two objects like Vectors, dataframes, etc. as arguments and results in a third object with the common data of both the objects.

How do you find the intersection of two lists in R?

In R, we can do this by using intersection function along with Reduce function.

What is intersection of lists?

Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list.


2 Answers

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"
like image 64
pengchy Avatar answered Sep 28 '22 08:09

pengchy


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.

like image 41
Ben Bolker Avatar answered Sep 28 '22 06:09

Ben Bolker