Compare vector elements in R, of different size

0

My intention here is to find the elements in common between a and b.

a <- seq(from=1, to=5, by=1)
b <- seq(from=5, to=13, by=1)
x <- which(a==b)

Warning message:
In a == b : longer object length is not a multiple of shorter object length.

How can I do this?

    
asked by anonymous 24.03.2017 / 18:21

2 answers

4

Use the command intersect :

a <- seq(from=1, to=5, by=1)
b <- seq(from=5, to=13, by=1)
intersect(a, b)
[1] 5
    
24.03.2017 / 20:16
3

Another way is to use the %in% operator:

> a %in% b
[1] FALSE FALSE FALSE FALSE  TRUE

The %in% operator returns a vector of TRUE or FALSE of the same size as the left vector. TRUE indicates that the element is present in the right vector and FALSE indicates that it is not.

Subsetting using the result of %in% , you find the elements that are at the intersection.

> a[a %in% b]
[1] 5
    
31.03.2017 / 20:07