Back to Practice
#0091
Clean Missing Values in R
EasyR12 min10 XP
Problem
Given scores <- c(10, NA, 20, NA, 30), replace NA values with the mean of non-missing values.
Why This Matters
Missing data appears constantly. R makes missing values explicit with NA, but many functions need na.rm = TRUE.
Examples
Example 1
Inputc(10, NA, 20, NA, 30)
Outputc(10, 20, 20, 20, 30)
The non-missing mean is 20.
Constraints
- Use is.na.
- Use na.rm = TRUE.
- Replace only missing values.
CodeR
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Mean imputation
Inputscores with NA
ExpectedNA values become 20
Mean is computed only from observed scores.
Hidden Test Categories
no missing valuesone missing valueall missing values discussion