Logical Comparisons

We can tests many flavors of logical conditions in R. Logical tests return a logical vector as the result. A logical vector 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

### Check equality
y == x
[1] FALSE
y == w
[1] TRUE

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

What values will the following four expressions 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

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 above 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 ensures 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.

Back to top