Debjyoti
Debjyoti

Reputation: 177

Obtain common elements from 2 lists of unequal length

My data structure is as follows:

xy
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
[[2]]
[1]  2  3  4  5  6  7  8  9 10 11 12

xyz
[[1]] 
[[1]] [[1]]
[1] 3 4 5 6 7 8 9 10
[[2]]
[[2]] [[1]]
[1]  5  6  7  8  9 10 11 12 13 14 15
[[3]]
[[3]] [[1]]
[1]  6  7  8  9 10 11 12

I want to find the common elements present in each subset of the list. My expected output is:

New_list
[[1]]
[1] 3 4 5 6 7 8 9 10
[[2]]
[1] 5  6  7  8  9 10 11 12 
[[3]]
[1] 6  7  8  9 10 11 12

Initially I tried the following command:

Map(intersect,xy,xyz)

However, its showing the following error:

Warning message: In mapply(FUN = f, ..., SIMPLIFY = FALSE) : longer argument not a multiple of length of shorter**

I am guessing it has got something to do with the unequal lengths of the lists as my command works fine with lists of equal length.

Upvotes: 1

Views: 252

Answers (2)

Andre Elrico
Andre Elrico

Reputation: 11480

l1 <- list(1:10,2:12)

l2 <- list(list(3:10),list(5:15),list(6:12))


lapply(unlist(l2,recursive=F),function(x){intersect(unlist(l1),x)})

Upvotes: 1

akrun
akrun

Reputation: 887118

We unlist the first list, flatten the second and loop over the list and use intersect

lapply(do.call(c, xyz), function(x) intersect(x, unlist(xy)))
#[[1]]
#[1]  3  4  5  6  7  8  9 10

#[[2]]
#[1]  5  6  7  8  9 10 11 12

#[[3]]
#[1]  6  7  8  9 10 11 12

data

xy <- list(1:10, 2:12)
xyz <- list(list(3:10), list(5:15), list(6:12))

Upvotes: 4

Related Questions