Search code examples
rvectorequalityintersect

Return TRUE/FALSE if common elements/no common elements between vectors


I'm looking for an efficient way to create a boolean vector which returns TRUE if one or more of a number of specified variables e.g. c(1,2,3) are in another vector e.g. c(4,5,6,1).

In this example the output sought would be TRUE as the element 1 is present in both vectors.

As far as I know %in% only permits checking one variable at a time and using the | operator is inefficient in this case given the number of potential variables I need to check for. Using intersect() returns logical(0) rather than FALSE, and sum(c(1,2,3) == c(4,5,6,1)) > 1 returns FALSE as the common elements are not in the same position.


Solution

  • Another option:

    vector1 <- c(1,2,3)
    vector2 <- c(4,5,6,1)
    
    any(Reduce(intersect, list(vector1, vector2)))
    

    Output:

    [1] TRUE