R / CHAPTER 03
Indexing and missing values
BeginnerSelect vector elements while handling unknown data explicitly.
By the end of this chapter
- Use one-based and logical indexing
- Recognize NA propagation
- Choose a missing-value policy
The idea
R uses one-based indices: the first element is x[1]. Positive indices select positions, negative indices exclude positions, and logical vectors select where their entries are true. Zero selects no position. Match a logical selector to the data it describes so recycling does not quietly change the selection. A comparison such as x >= 10 builds a vector of logical results rather than one overall answer.
NA represents a missing value, and calculations or comparisons involving it often remain unknown. Use is.na to test for missingness; comparing a value to NA does not answer whether it is missing. Many summary functions accept na.rm = TRUE, but removing missing entries is a policy choice. Decide what an entirely missing input should mean before treating its summary as a meaningful measurement.
x <- c(4, NA, 9, 2)
keep <- !is.na(x) & x >= 4
cat(x[keep], sep = ",")
cat("
")
cat(sum(x, na.rm = TRUE), "
", sep = "")4,9 15
The explicit missingness check makes the selector false at the missing position. The sum excludes that missing value and adds the three known numbers.
Try it yourself
Select all known values below zero, preserving their order, and return an empty vector when none qualify.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING