Logical Values and Comparisons
Prerequisites: Vectors
A logical value is TRUE or FALSE. Comparisons produce logicals —
and, like everything in R, they work on whole vectors.
age <- 20
age > 18
age == 21
age != 21
ages <- c(12, 25, 37, 8)
ages >= 18
[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE TRUE TRUE FALSE
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
> < |
greater / less than |
>= <= |
greater / less or equal |
Combining conditions
ages <- c(12, 25, 37, 8, 70)
ages >= 18 & ages < 65
ages < 13 | ages > 65
!(ages > 30)
[1] FALSE TRUE TRUE FALSE FALSE
[1] TRUE FALSE FALSE TRUE TRUE
[1] TRUE TRUE FALSE TRUE FALSE
&(and),|(or), and!(not) work element by element.&&and||work on single values and are used inifconditions (next lessons).
Counting with logicals
TRUE counts as 1 and FALSE as 0, so sum and mean answer "how
many" and "what proportion":
ages <- c(12, 25, 37, 8, 70)
sum(ages >= 18)
mean(ages >= 18)
any(ages > 65)
all(ages > 0)
[1] 3
[1] 0.6
[1] TRUE
[1] TRUE
This is an everyday data-analysis idiom: "60% of the people are adults".
Common mistakes
- Writing
TandFinstead ofTRUEandFALSE. They work, butTandFcan be overwritten as ordinary variables — always write the full words. - Using
=instead of==in a comparison.