typestar

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

  1. is.na flags gaps; summing it counts them.
  2. na.rm = TRUE excludes them from statistics.
  3. complete.cases keeps only fully observed rows.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Reshaping & combining, step 7 of 8 in Data frames in base R.

← Previous Next →

Missing data in other languages