Logical — TRUE, FALSE and NA
Logical values are TRUE and FALSE, which count as 1 and 0 in arithmetic, plus NA for an unknown value that spreads through calculations unless you remove it or test for it with is.na().
Track missing truth values through conditions instead of silently treating them as false.
Plot F's harvest was never weighed. Suddenly the average weight comes back as NA, and a filter that worked yesterday behaves strangely. Logical values drive every filter and decision in R, and their third value, NA, is where most surprises come from.
The rule
TRUE counts as 1, FALSE as 0, and NA means unknown.
Logical values come from comparisons, or you type them directly:
watered <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
sum(watered) # 3, the number of watered plots
mean(watered) # 0.6, the share of plots watered
any(watered) # TRUE, at least one is TRUE
all(watered) # FALSE, not every one is TRUE
which(watered) # 1 3 4, the positions of the TRUEsBecause TRUE counts as 1 and FALSE as 0, sum() of a logical vector is a count and mean() is a proportion. This is one of R's most useful habits.
Always type TRUE and FALSE in full. T and F usually work, but they are ordinary variables that anyone can overwrite, for example with T <- 0, while TRUE and FALSE are reserved words.
NA is "not available": a value exists but nobody knows it. It is logical by default (typeof(NA) is "logical") and it can sit in any vector:
kg <- c(12.5, 8, 15, 3.5, 6, NA) # plot F was not weighed
mean(kg) # NA
mean(kg, na.rm = TRUE) # 9
kg > 7 # TRUE TRUE TRUE FALSE FALSE NA
kg == NA # NA NA NA NA NA NA
is.na(kg) # FALSE FALSE FALSE FALSE FALSE TRUENA spreads: an unknown value makes any result that depends on it unknown. Many summary functions accept na.rm = TRUE to drop NAs first. To find NAs, always use is.na(), because x == NA asks "is x equal to an unknown value?", and the only honest answer is NA.
Do not confuse NA with NULL. NA is a placeholder for one missing value (length(NA) is 1); NULL means nothing at all (length(NULL) is 0).