SteveM
SteveM

Reputation: 2301

Exhaustively intersect 2 or more lists of integer vectors

Is there a way to exhaustively intersect 2 or more lists of integer vectors in R without using for loops? Example for the 2 list (3x2) case:

set.seed(7)
x <- 1:25
x1 <- sample(x, 11)
x2 <- sample(x, 7)
x3 <- sample(x, 15)
list1 <- list(x1 = x1, x2 = x2, x3 = x3)

y <- 1:20
y1 <- sample(y, 13)
y2 <- sample(y, 10)
list2 <- list(y1 = y1, y2 = y2)

So intersect x1 with y1, y2; x2 with y1, y2;, x3 with y1, y2

Upvotes: 2

Views: 48

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101149

You can try the code below

> outer(list1, list2, Vectorize(intersect))
   y1        y2
x1 Integer,6 Integer,5
x2 Integer,4 Integer,4
x3 Integer,8 Integer,5

If you want to explicitly see the intersection, you can try

> outer(list1, list2, FUN = Vectorize(function(x, y) toString(intersect(x, y))))
   y1                           y2
x1 "2, 15, 8, 3, 20, 11"        "10, 19, 8, 21, 18"
x2 "20, 8, 15, 6"               "12, 19, 8, 18"
x3 "16, 4, 11, 6, 2, 20, 8, 15" "16, 21, 8, 23, 12"

Upvotes: 2

s_baldur
s_baldur

Reputation: 33498

With lapply():

lapply(list1, function(x) lapply(list2, function(y) intersect(x, y)))

Upvotes: 2

Related Questions