Multiple List Crossing in R

I have 4 lists

a <- list(1,2,3,4) b <- list(5,6,7,8) c <- list(7,9,0) d <- list(12,14) 

I would like to know which of the lists have common elements. In this example, lists b and c have a common element of 7.

The brute-force approach should be to take each combination of lists and find an intersection. Is there any other efficient way to do this in R?

Another approach would be to make a single list from all the lists and find duplicates. Then, perhaps, we can have a display function indicating which source lists these duplicates are from. But I'm not sure how to do this. I came across this post

Find duplicate row indices

I was thinking if we could change this to find out the actual duplicate listings.

I have to repeat this process for many groups of lists. Any suggestions or ideas are welcome! thanks in advance

+2
list r set-intersection
source share
1 answer

How about using this double sapply ?

 l <- list(a,b,c,d) sapply(seq_len(length(l)), function(x) sapply(seq_len(length(l)), function(y) length(intersect(unlist(l[x]), unlist(l[y]))))) [,1] [,2] [,3] [,4] [1,] 4 0 0 0 [2,] 0 4 1 0 [3,] 0 1 3 0 [4,] 0 0 0 2 

Interpretation: for example. the element [1,2] of the matrix shows you how many elements the first element of the list l (in this case, the subscript a ) has in conjunction with the second element of the list (ie, sublist b )

Or, alternatively, just see subscription indexes that have a common meaning with some other sublist:

 which(sapply(seq_len(length(l)), function(x) length(intersect(l[[x]], unlist(l[-x])))) >= 1) [1] 2 3 
+5
source share

All Articles