David Moore
David Moore

Reputation: 968

Finding Values Present in Two or More Unequal-Length Vectors

I have the following two numeric vectors:

A <- c(1, 3, 5, 7, 9)
B <- c(2, 3, 4, 5, 6, 10, 12, 13)

I want to generate a new vector C that contains the values that are present in both A and B (not the positions at which these values are found). The result should be:

C <- c(3, 5)

I also want to generate a vector D containing the values present in A but not present in B and a vector E containing the values present in B but not A.

D <- c(1, 7, 9)
E <- c(2, 4, 6, 10, 12, 13)

What is the best way to do this using base R? Thanks!

Upvotes: 0

Views: 74

Answers (2)

boski
boski

Reputation: 2467

A <- c(1, 3, 5, 7, 9)
B <- c(2, 3, 4, 5, 6, 10, 12, 13)
C <- A[!A%in%B]
D <- B[!B%in%A]

Which yields

> C
[1] 1 7 9
> D
[1]  2  4  6 10 12 13

Upvotes: 0

DJV
DJV

Reputation: 4863

You can use the base R function intersect().

In addition, generally speaking I wouldn't use C as a variable name as it really close to c(), which might cause you problems.

A <- c(1, 3, 5, 7, 9)
B <- c(2, 3, 4, 5, 6, 10, 12, 13)

Inter <- intersect(A, B)

[1] 3 5

For the opposite of `intersect()':

#taken from here:https://www.r-bloggers.com/outersect-the-opposite-of-rs-intersect-function/
outersect <- function(x, y) {
  sort(c(setdiff(x, y),
         setdiff(y, x)))
}

outersect(A, B)
[1]  1  2  4  6  7  9 10 12 13

Upvotes: 3

Related Questions