Compare vector elements in R of different sizes

Asked

Viewed 1,348 times

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 that?

  • The question is very confusing. What you want is to find the common elements between a and b? For example, the answer to your code above should be 5?

  • exact. thank you.

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

3

Another way is to use the operator %in%:

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

The operator %in% returns a TRUE or FALSE vector 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.