R Booleans

R represents true and false with the logical type, which underlies every comparison you write and every condition you test.

The Logical Type

R represents true/false values with the reserved words TRUE and FALSE (or their shorthand T and F), stored under the type "logical". Comparisons such as ==, !=, <, >, <=, and >= all produce a logical value.

Example

is_active <- TRUE
class(is_active)
# "logical"

5 > 3
# TRUE

"cat" == "dog"
# FALSE

Combining Conditions

Use & and | to combine logical values element by element (handy inside vectors), and && / || to combine single conditions with short-circuit evaluation — stopping as soon as the answer is known — which is the form R recommends inside if() statements. ! negates a logical value.

Example

age <- 20
has_id <- TRUE
age >= 18 && has_id
# TRUE

!has_id
# FALSE

Logical Values Are Secretly Numbers

R treats TRUE as 1 and FALSE as 0 whenever a logical value is used in arithmetic, which makes sum() a quick way to count how many elements of a logical vector are TRUE.

Example

scores <- c(45, 82, 91, 60, 77)
passing <- scores >= 60
passing
# FALSE  TRUE  TRUE  TRUE  TRUE

sum(passing)
# 4

Truth Tables at a Glance

ABA & BA | B
TRUETRUETRUETRUE
TRUEFALSEFALSETRUE
FALSETRUEFALSETRUE
FALSEFALSEFALSEFALSE
Note: Avoid comparing directly to TRUE or FALSE, like if (x == TRUE) — just write if (x), since x is already a logical value.

Exercise: R Booleans

Why is it safer to write TRUE and FALSE in full rather than the shorthand T and F?