Logical — TRUE, FALSE and NA
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).
The shortcut
For any expression involving NA, ask: "Could the unknown value change the answer?" If yes, the result is NA. If no, R gives the definite answer.
NA & FALSEis FALSE: whatever NA is, "and FALSE" is FALSE.NA & TRUEis NA: the answer depends on the unknown.NA + 1is NA: an unknown number plus one is still unknown.
Compare
kg > 7gives TRUE TRUE TRUE FALSE FALSE NA. Plot F's comparison is unknown.
Drills
Answer fast — trust the rule.
With watered <- c(TRUE, FALSE, TRUE, TRUE, FALSE), what is sum(watered)?
What is mean(watered)?
What does NA == NA return?
What does NA & FALSE return?
Which is the correct way to find the missing values in kg?
Remember
- TRUE counts as 1, FALSE as 0, and NA means unknown.
- Shortcut: could the unknown change the answer? If so, the result is NA.
- Trap: testing with
== NA, forgettingna.rm = TRUE, and trustingTandF.
