Types and Missing Values
Missing Values
Skipping NA
NA marks missing data. Logical masks and is.na let a script select only known values.
Program
Play the script to watch the missing score get excluded before the average is computed.
missing_values.R
Replay: real traced execution (multi-file project)
scores <- c(10, NA, 8)
known <- !is.na(scores)
average <- mean(scores[known])
cat(average, "\n", sep = "")
scores ← 10, NA, 8
1scores <- c(10, NA, 8)2known <- !is.na(scores)values this step10, NA, 8scoresknown ← TRUE, FALSE, TRUE
1scores <- c(10, NA, 8)2known <- !is.na(scores)3average <- mean(scores[known])values this stepTRUE, FALSE, TRUEknown10, NA, 8scoresaverage ← 9
2known <- !is.na(scores)3average <- mean(scores[known])4cat(average, "\n", sep = "")values this step9average10, 8scores[known]cat(average, " ", sep = "")
3average <- mean(scores[known])4cat(average, "\n", sep = "")output9values this step9average
Follow the Known Values
scoresstarts as10,NA, and8.!is.na(scores)marks known values asTRUE.knownbecomesTRUE,FALSE,TRUE.scores[known]keeps only10and8.meanreturns9, andcatprints9. | score | known? | used in mean | | --- | --- | --- | | 10 | TRUE | yes | | NA | FALSE | no | | 8 | TRUE | yes |
NA
`NA` represents a missing value in R.
is.na
`is.na(scores)` returns `TRUE` where values are missing.
logical mask
A logical vector can select matching positions from another vector.
Exercise: missing_values.R
Reproduce the printed average 9, then replace NA with 6 and predict the new average before running it.