Subsetting and Cleaning
Logical Filters
Keeping Matches
Comparisons over vectors produce logical masks. Those masks keep the values that match a condition.
Program
Play the script to see passing scores selected from a longer vector.
logical_filters.R
Replay: real traced execution (multi-file project)
scores <- c(65, 82, 91, 74)
passed <- scores >= 80
selected <- scores[passed]
cat(paste(selected, collapse = ","), "\n", sep = "")
scores ← 65, 82, 91, 74
1scores <- c(65, 82, 91, 74)2passed <- scores >= 80values this step65, 82, 91, 74scorespassed ← FALSE, TRUE, TRUE, FALSE
1scores <- c(65, 82, 91, 74)2passed <- scores >= 803selected <- scores[passed]values this stepFALSE, TRUE, TRUE, FALSEpassed65, 82, 91, 74scoresselected ← 82, 91
2passed <- scores >= 803selected <- scores[passed]4cat(paste(selected, collapse = ","), "\n", sep = "")values this step82, 91selectedFALSE, TRUE, TRUE, FALSEpassedcat(paste(selected, collapse = ","), " ", sep = "")
3selected <- scores[passed]4cat(paste(selected, collapse = ","), "\n", sep = "")output82,91values this step82, 91selected
Follow the Filter
scoresstarts as65,82,91, and74.scores >= 80checks each value.passedbecomesFALSE,TRUE,TRUE,FALSE.scores[passed]keeps82and91.- The script prints
82,91. | score | passed? | selected? | | --- | --- | --- | | 65 | FALSE | no | | 82 | TRUE | yes | | 91 | TRUE | yes | | 74 | FALSE | no |
comparison
`scores >= 80` compares every score at once.
filter
`scores[passed]` keeps positions where `passed` is `TRUE`.
collapse
`paste(..., collapse = ",")` joins many values into one string.
Exercise: logical_filters.R
Reproduce 82,91, then identify the two TRUE positions that selected those scores.