# How to Compare Vectors in R?

## Problem –

You want to compare two vectors or you want to compare an entire vector against a scalar.

## Solution –

The comparison operators (==, !=, <, >, <=, >=) can perform an element by element comparison of two vectors. They can also compare a vector’s element against a scalar.

R has two logical Values TRUE and FALSE. The comparison operators compare two values and return TRUE and FALSE depending upon the result of comparison.

> a <- 3
> a == pi
 FALSE
> a != pi
 TRUE
> a < pi
 TRUE
> a > pi
 FALSE
> a <= pi
 TRUE
> a >= pi
 FALSE

You can also do element by element comparison of two vectors.

> a <- c(5, 10, 15)
> b <- c(10, 10, 10)
> a == b
 FALSE  TRUE FALSE
> a != b
  TRUE FALSE  TRUE
> a < b
  TRUE FALSE FALSE
> a > b
 FALSE FALSE  TRUE
> a <= b
  TRUE  TRUE FALSE
> a >= b
 FALSE  TRUE  TRUE

You can also compare a vector with a scalar.

> a <- c(5, 10, 15)
> a == 5
  TRUE FALSE FALSE
> a != 5
 FALSE  TRUE  TRUE

After comparing two vectors, you may want to know whether any of the comparison were true or whether all the comparison were true. The any and all functions handle those tests. They both test a logical vector.

> a <- c(3, pi, 4)
> any(a == pi)
 TRUE
> all(a == 0)
 FALSE

Rating: 1 out of 5.

Posted in RTagged