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 = "")
  1. scores ← 10, NA, 8

    1scores <- c(10, NA, 8)2known <- !is.na(scores)
    values this step10, NA, 8scores
  2. known ← TRUE, FALSE, TRUE

    1scores <- c(10, NA, 8)2known <- !is.na(scores)3average <- mean(scores[known])
    values this stepTRUE, FALSE, TRUEknown10, NA, 8scores
  3. average ← 9

    2known <- !is.na(scores)3average <- mean(scores[known])4cat(average, "\n", sep = "")
    values this step9average10, 8scores[known]
  4. cat(average, " ", sep = "")

    3average <- mean(scores[known])4cat(average, "\n", sep = "")
    output9
    values this step9average

Follow the Known Values

  1. scores starts as 10, NA, and 8.
  2. !is.na(scores) marks known values as TRUE.
  3. known becomes TRUE, FALSE, TRUE.
  4. scores[known] keeps only 10 and 8.
  5. mean returns 9, and cat prints 9. | 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.