0Pricing
R Academy · Lesson

Detecting and Counting Missing Values

Use is.na(), anyNA(), and sum(is.na()) to audit missing data.

is.na() — The Core Detection Tool

is.na(x) tests each element of x and returns a logical vector of the same length, with TRUE where the value is NA (or NaN). This is the fundamental tool for detecting missing values.

heights <- c(175, NA, 162, 188, NA, 170, NA, 165)
cat('Heights:', heights, '
')
cat('is.na() :', is.na(heights), '
')
cat('!is.na():', !is.na(heights), '
')

Counting NAs with sum(is.na())

Because TRUE == 1 and FALSE == 0 in arithmetic, sum(is.na(x)) counts the total number of missing values. mean(is.na(x)) gives the proportion of missing values.

survey <- c(8, NA, 6, NA, 9, 7, NA, 5, NA, 8)
cat('Survey responses:', survey, '
')
cat('Total NAs:    ', sum(is.na(survey)), '
')
cat('Total present:', sum(!is.na(survey)), '
')
cat('NA proportion:', mean(is.na(survey)), '
')
cat('NA percentage:', mean(is.na(survey)) * 100, '%
')

All lessons in this course

  1. Understanding NA in R
  2. Detecting and Counting Missing Values
  3. Removing and Replacing NA Values
  4. NA in Calculations and Aggregations
← Back to R Academy