Logical Comparisons

We can test many flavors of logical conditions in R. Logical tests return a logical value as the result. A logical value takes the value of TRUE whenever the tested condition is satisfied and FALSE when the tested condition is not satisfied.

Equality

The simplest logical test is an equality check. To check if two objects are equal, we use the ‘equality operator’, ==.

## Define some objects to play with
y <- 5
x <- 7
w <- 5

Explain: y == x is FALSE because 5 is not equal to 7. y == w is TRUE because both objects store the value 5. Notice == (two equals signs) is a comparison, while <- and a single = are used for assignment. Mixing these up is one of the most common beginner mistakes in R.

Greater/Lesser

We can also check the usual greater-than/less-than conditions with >, <, >=, <=.

y > x  # greater than
[1] FALSE
y >= x # greater than or equal to
[1] FALSE
y < x  # less than
[1] TRUE
y <= x # less than or equal to
[1] TRUE
Practice: Predict, Then Run

Given y <- 5 and w <- 5, predict what value each of the following expressions will return.

y > w
y >= w
y < w
y <= w
y > w
[1] FALSE
y >= w
[1] TRUE
y < w
[1] FALSE
y <= w
[1] TRUE

Since y and w store the same value, y > w and y < w are both FALSE (neither is strictly greater or less than the other), while y >= w and y <= w are both TRUE, since “greater than or equal to” and “less than or equal to” are satisfied whenever the values are equal.

Logical Negation

We can negate any logical condition by prepending the ! character.

y > x
[1] FALSE
!y > x
[1] TRUE
y == w
[1] TRUE
!y == w
[1] FALSE

Rather than negating an equality check, we will typically use the special “not-equal” operator, !=.

y == w
[1] TRUE
y != w
[1] FALSE

Combining Conditions

We can create more complex logical conditions with the AND and OR operators: & and |.

y == w & y < x
[1] TRUE
y == w & y > x
[1] FALSE
y == w | y > x
[1] TRUE
Practice

Use a single line of code to generate a logical value (i.e., TRUE/FALSE) indicating if the value of the weeks object you created earlier is evenly divisible by 7.

  • Use x %% 7 to calculate the remainder after dividing x by 7.
  • If you’re getting unexpected results, consider using parentheses to ensure the intended order of operations.
  • In R, the modulo operator, %%, takes precedence over arithmetic operations like multiplication.
(weeks %% 7) == 0
[1] FALSE

If the remainder of dividing weeks by 7 is zero, we know that the value of weeks is evenly divisible by 7.

Quick Check

  • What’s the difference between = and == in R?
  • If a <- 3 and b <- 4, what does a != b return?
  • Write (but don’t necessarily run) an expression that checks whether a is greater than 1 and less than 10.
Back to top