Home > Software engineering >  Get common values in three vectors at least repeated once between vectors
Get common values in three vectors at least repeated once between vectors

Time:11-28

I want to compare an undetermined number of vectors and get the common values in at least two of them.

As an example, let’s just use three vectors:

x <- c(1,3,5,7,9)
y <- c(3,6,8,9,4)
z <- c(2,3,4,5,7,9)

Reduce(intersect, list(x,y,z))

# or

intersect(x, intersect(y,z))

[1] 3 9

Expected result is:

[1] 3 4 5 7 9 

CodePudding user response:

We may stack a named list to two column data.frame, get the table, check if the row wise sum is greater than or equal to 2, return the names that are TRUE for those

names(which(rowSums(table(stack(list(x= x, y = y, z = z))) > 0) >= 2))
[1] "3" "4" "5" "7" "9"

If we want to use pairwise intersect for all combinations, use combn and then Reduce with union

sort(Reduce(union, combn(list(x, y, z), 2,
    FUN = function(x) intersect(x[[1]], x[[2]]), simplify = FALSE)))
[1] 3 4 5 7 9

CodePudding user response:

You can put the vectors in one large vector:

vec <- unlist(list(x, y, z))

Or, if you may have duplicates within a single contributing vector:

vec <- unlist(lapply(list(x, y, z), unique))

Then, subset based on presence of duplicates (and sort if needed):

sort(unique(vec[duplicated(vec)]))

Output

[1] 3 4 5 7 9
  •  Tags:  
  • r
  • Related