How to Compare Vectors in R

03.23.2021

R has many helpful features for vectors. One such feature is comparisons. When comparing vectors in R, each element will be compared and a full vector will be returned. Let's take a look at a few examples.

x = c(1, 2, 3)
y = c(4, 5, 6)

x < y
# [1] TRUE TRUE TRUE

x > y
# [1] FALSE FALSE FALSE

x == y
# [1] FALSE FALSE FALSE

We can also compare a vector and a scaler value, which also us to use comparision like other vector operations in math.

x = c(1, 2, 3)
y = 5

x < y
# [1] TRUE TRUE TRUE

Finally, R also provides some helpfuly methods for searching and comparing values in vectors. Let's look at two examples.

First we have any which will return True and any value in the vector matches the comparison.

x = c(1, 2, 3)

any(x > 2)

# [1] TRUE

Then, we have all which only returns true if all elements match the comparison.

x = c(1, 2, 3)

any(x < 0)

# [1] FALSE