Combine any vectors that have shared values

Viewed 47

I have a large list of vectors polyInt and would like to combine them based on shared values, removing any duplicate values. For example:

polyInt = list(c(1,2,3,4),
               c(4,5,6),
               c(7,8,9),
               c(9,10,11,12))

Would reduce to:

combinedVects = list(c(1,2,3,4,5,6),
                     c(7,8,9,10,11,12))

Because the first two and last two vectors in polyInt have common values.

I'm at a loss as to whether there is a convenient way to do this. Any help would be greatly appreciated!

EDIT: Here is my actual list, not a simplified example. Some of the list items are single values, so this may affect the solution.

vectList = list(c(1,5,6,10,12,20),
                c(2,4,10),
                3,
                c(2,4,21),
                c(1,5,9,10,12,20),
                c(6,11,34),
                c(7,9,10,33),
                c(8,17,23),
                c(1,5,7,9,12,33),
                c(1,2,5,7,10,33),
                c(6,11,19),
                c(1,5,9,12,13,20,22,24),
                c(12,13)
                14,
                c(15,16,19),
                c(15,16,31),
                c(8,17,26),
                18,
                c(11,15,19,25,31,36),
                c(1,5,12,20,22),
                c(4,21),
                c(12,20,22,24),
                c(8,23,29,30),
                c(12,22,24),
                c(19,25),
                c(17,26),
                27,
                c(28,30),
                c(23,29),
                c(23,28,30,35),
                c(16,19,31),
                32,
                c(7,9,10,33),
                c(6,34),
                c(30,35),
                c(19,36))
1 Answers

In base R, you can use intersect and split:

inter <- lapply(seq(polyInt), \(n) intersect(polyInt[[n]], unlist(polyInt[-n])))
combinedVects <- lapply(split(polyInt, unlist(inter)), \(x) unique(unlist(x)))

#> combinedVect
# $`4`
# [1] 1 2 3 4 5 6
# 
# $`9`
# [1]  7  8  9 10 11 12

Note: \ can replace function in lambda-like functions since R 4.1.

Related