# How to Compare Values in Logical Vectors in R

To build logical vectors in R, you’d better know how to compare values, and R contains a set of operators that you can use for this purpose.

Operator | Result |
---|---|

x == y |
Returns TRUE if x exactlyequals y |

x != y |
Returns TRUE if x differsfrom y |

x > y |
Returns TRUE if x is largerthan y |

x >= y |
Returns TRUE if x is largerthan or exactly equal to y |

x < y |
Returns TRUE if x issmaller than y |

x <= y |
Returns TRUE if x issmaller than or exactly equal to y |

x & y |
Returns the result of x and y |

x | y |
Returns the result of x or y |

! x |
Returns not x |

xor( x, y ) |
Returns the result of x xor y (x or y but not x andy) |

All these operators are, again, vectorized. You can compare a whole vector with a value.

Let’s assume that you have two vectors containing the number of baskets that Granny and her friend Geraldine scored in the six games of this basketball season:

> baskets.of.Granny <- c(12,4,4,6,9,3) > baskets.of.Geraldine <- c(5,3,2,2,12,9)

In this imaginary All-Star Grannies basketball game, to find out which games Granny scored more than five baskets in, you can simply use this code:

> baskets.of.Granny > 5 [1] TRUE FALSE FALSE TRUE TRUE FALSE

You can see that the result is the first, fourth, and fifth games. This example works well for small vectors like this one, but if you have a very long vector, counting the number of games would be a hassle. For that purpose, R offers the delightful which() function. To find out which games Granny scored more than five baskets in, you can use the following code:

> which(baskets.of.Granny > 5) [1] 1 4 5

With this one line of code, you actually do two different things: First, you make a logical vector by checking every value in the vector to see whether it’s greater than five. Then you pass that vector to the which() function, which returns the indices in which the value is TRUE.

The which() function takes a logical vector as argument. Hence, you can save the outcome of a logical vector in an object and pass that to the which() function, as in the next example. You also can use all these operators to compare vectors value by value. You can easily find out the games in which Geraldine scored fewer baskets than Granny like this:

> the.best <- baskets.of.Geraldine < baskets.of.Granny > which(the.best) [1] 1 3 4

Always put spaces around the less than (<) and greater than (>) operators. Otherwise, R may mistake x < -3 for the assignment x <- 3. The difference may seem small, but it has a huge effect on the result.

Technically, you also can use the equal sign (=) as an assignment to prevent this problem, but = also is used to assign values to arguments in functions. In general, <- is the preferred way to assign a value to an object, but quite a few coders disagree. So, it’s up to you. Most use <- in their work.