Search code examples
rstringvectorintersect

Extract non intersected element from a string vector in R


I have 2 string vectors, and I have intersected them in order to get the intersected string vector, but now, I need to get the 2 other string vectors without the intersected elements.

That is, vector.1 without intersected.vector elements, and vector.2 without intersected.vector elements. How can I do that?


Solution

  • I hope this simple example illustrates what you are asking for:

    vector.1 <- LETTERS[1:4]
    vector.2 <- LETTERS[3:6]
    
    > vector.1
    [1] "A" "B" "C" "D"
    > vector.2
    [1] "C" "D" "E" "F"
    
    intersected.vector <- intersect(vector.1, vector.2)
    > intersected.vector
    [1] "C" "D"
    
    new_vec1 <- vector.1[-which(vector.1 %in% intersected.vector)]
    > new_vec1
    [1] "A" "B"
    
    new_vec2 <- vector.2[-which(vector.2 %in% intersected.vector)]
    > new_vec2
    [1] "E" "F"