R Booleans
A logical value (a boolean) is either TRUE or FALSE. Logicals are the answer to yes/no questions such as "is this number bigger than that one?", and they drive every if statement and every filter you will write.
is_open <- TRUE
has_discount <- FALSE
class(is_open)
10 > 9
10 == 9
"a" != "b"[1] "logical"
[1] TRUE
[1] FALSE
[1] TRUE
Tip: R also accepts the abbreviations
TandF, but they are ordinary variables that can be overwritten (T <- 0). Always writeTRUEandFALSEin full.
Comparisons produce logical vectors
Because R is vectorised, comparing a vector with a value gives one TRUE/FALSE per element. That is how you filter data:
ages <- c(15, 22, 17, 34, 19)
ages >= 18
ages[ages >= 18]
sum(ages >= 18) # TRUE counts as 1
mean(ages >= 18) # proportion of adults[1] FALSE TRUE FALSE TRUE TRUE
[1] 22 34 19
[1] 3
[1] 0.6
Counting with sum() and computing proportions with mean() works because TRUE is converted to 1 and FALSE to 0 in arithmetic.
Combining conditions
| Operator | Meaning |
|---|---|
!x |
NOT |
x & y |
AND (element-wise) |
x | y |
OR (element-wise) |
xor(x, y) |
exclusive OR |
x && y, x || y |
AND / OR for a single value, used in if |
temp <- c(12, 25, 31, 18)
sunny <- c(TRUE, TRUE, FALSE, TRUE)
temp > 20 & sunny
temp > 30 | !sunny
xor(TRUE, FALSE)[1] FALSE TRUE FALSE FALSE
[1] FALSE FALSE TRUE FALSE
[1] TRUE
&& and || look only at a single value and stop as soon as the answer is known ("short-circuit"). In R 4.3 and later, giving them a vector longer than 1 is an error, so use them only for single conditions:
x <- NULL
is.null(x) || x > 5 # the right side is never evaluated
c(TRUE, FALSE) && TRUE[1] TRUE
Error in c(TRUE, FALSE) && TRUE : 'length = 2' in coercion to 'logical(1)'
any(), all() and which()
scores <- c(72, 88, 95, 61)
any(scores > 90)
all(scores >= 60)
which(scores > 80)
isTRUE(c(TRUE, TRUE))[1] TRUE
[1] TRUE
[1] 2 3
[1] FALSE
which() returns the positions where the condition is TRUE. isTRUE() is TRUE only for a single, non-missing TRUE, which makes it a safe test in if conditions.
Logical NA
NA is also a logical value meaning "unknown". Logic with NA follows common sense: TRUE | NA is TRUE (whatever the unknown is, the result is true), but TRUE & NA is unknown:
TRUE | NA
TRUE & NA
FALSE & NA
NA > 1[1] TRUE
[1] NA
[1] FALSE
[1] NA
Test yourself
What does sum(c(3, 8, 1, 9) > 5) return?
- 17
- 2
- TRUE
- 4
Which operator should you use to combine two single conditions in an if?
- &
- &&
- and
- +
What is FALSE & NA?
- NA
- FALSE
- TRUE
- An error