AnyCompiler

NA Handling

NA is not an exception, and it's not something R stops to tell you about every time it shows up — it's a real value that quietly poisons any arithmetic it touches. sum() of a vector containing even one NA returns NA, not a partial sum and not an error, because R has no way to know what the missing value should have contributed. is.na() checks, element by element, which positions actually hold NA. Many aggregate functions — sum(), mean(), and others — accept na.rm = TRUE to explicitly say "skip the missing values and compute the answer from what's left", which is the deliberate, opt-in way to work around the default propagation.

x <- c(1, 2, NA, 4)
print(sum(x))
print(sum(x, na.rm = TRUE))
print(is.na(x))
Output
[1] NA
[1] 7
[1] FALSE FALSE  TRUE FALSE

sum(x) with no extra argument returned NA, exactly as the earlier as.numeric("abc") warning foreshadowed — one missing value is enough to make the whole sum unknown. sum(x, na.rm = TRUE) explicitly opted out of that caution and computed 1 + 2 + 4 = 7. is.na(x) shows exactly where the NA lives: position 3, and nowhere else. Next: writing your own functions with vectors — combining everything so far into functions that take a whole vector as input and still need no loop.

Practice exercise

Given x <- c(5, NA, 15, NA), print is.na(x), then print mean(x, na.rm = TRUE).