NA in Calculations and Aggregations
Control NA behavior in mean(), sum(), and other aggregate functions.
The na.rm Parameter
Most R aggregation functions accept a na.rm argument (NA remove). When set to TRUE, the function ignores NA values before computing the result. By default, na.rm = FALSE, so NAs propagate.
scores <- c(88, NA, 72, 95, NA, 81, 67)
cat('With na.rm=FALSE (default):
')
cat(' mean:', mean(scores), '
') # NA
cat(' sum: ', sum(scores), '
') # NA
cat('With na.rm=TRUE:
')
cat(' mean:', mean(scores, na.rm = TRUE), '
') # 80.6
cat(' sum: ', sum(scores, na.rm = TRUE), '
') # 403mean() with na.rm
mean(x, na.rm = TRUE) computes the arithmetic mean of the non-missing values. The denominator is the count of present values, not the total length.
temperatures <- c(22.1, NA, 19.8, 25.1, NA, 17.3, 20.0)
cat('Total elements:', length(temperatures), '
')
cat('Present elements:', sum(!is.na(temperatures)), '
')
cat('Mean (na.rm=TRUE):', mean(temperatures, na.rm = TRUE), '
')
# Manual verification
cat('Manual mean:', sum(temperatures, na.rm=TRUE) / sum(!is.na(temperatures)), '
')All lessons in this course
- Understanding NA in R
- Detecting and Counting Missing Values
- Removing and Replacing NA Values
- NA in Calculations and Aggregations