-1

I'm trying and failing to get the number of elements in the intersect between several vectors at once in R: I have several character vectors of different lengths (unique elements) and want to get the number of elements shared between each pair of vectors.

Essentially, this means something like length(intersect(a,b)), but repeated several times/as a cross-tabulation over all combinations of vectors.

I feel like this is a simple case involving something like the apply() family, but I can't seem to figure this out... :-/

Thank you for any advice!

apeshifter
  • 19
  • 4
  • Maybe this is what you want https://stackoverflow.com/questions/3695677/how-to-find-common-elements-from-multiple-vectors – Ronak Shah Mar 11 '20 at 00:07

2 Answers2

0

You can use Reduce; here is a minimal reproducible example

a1 <- 1:5
a2 <- 3:6
a3 <- 4:9

Reduce(intersect, list(a1, a2, a3))
#[1] 4 5

The key is to store the vectors in a list.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • Thanks a lot! I had already tried the Reduce function but could not get the length function to work on that. – apeshifter Mar 31 '20 at 14:51
0

To get the intersection of all combinations of vectors you can do:

l <- list(a1 = 1:5, a2 = 3:6, a3 = 4:9)

intsct_list <- combn(seq_along(l), 2, function(x) intersect(l[[x[1]]], l[[x[2]]]), simplify = FALSE)

names(intsct_list) <- combn(names(l), 2, paste0, collapse = "")

lengths(intsct_list)  

a1a2 a1a3 a2a3 
   3    2    3 
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
  • Thank you so much; this is exactly what I was looking for! (Sorry, however, for being so very late to respond!) – apeshifter Mar 31 '20 at 14:50