Missing data in R
Detecting, removing, and imputing NA values.
values <- c(3, NA, 7, NA, 12)
which_missing <- is.na(values)
how_many <- sum(is.na(values))
complete <- values[!is.na(values)]
avg <- mean(values, na.rm = TRUE)
filled <- ifelse(is.na(values), avg, values)
df <- data.frame(a = c(1, NA), b = c(NA, 4))
clean_rows <- df[complete.cases(df), ]
How it works
is.naflags gaps; summing it counts them.na.rm = TRUEexcludes them from statistics.complete.caseskeeps only fully observed rows.
Keywords and builtins used here
cifelsemeansum
The run, in numbers
- Lines
- 11
- Characters to type
- 292
- Tokens
- 94
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.
Step 4 of 4 in Reshaping & combining, step 7 of 8 in Data frames in base R.