Types and Missing Values
Factors
Ordered Categories
Factors store categorical values with known levels. Ordered factors keep category order separate from alphabetical order.
Program
Play the script to watch text priorities become an ordered factor and then return to text.
factors.R
Replay: real traced execution (multi-file project)
levels <- c("low", "medium", "high")
priority <- factor(c("high", "low"), levels = levels, ordered = TRUE)
first_level <- as.character(priority[1])
cat(first_level, "\n", sep = "")
levels ← low, medium, high
1levels <- c("low", "medium", "high")2priority <- factor(c("high", "low"), levels = levels, ordered = TRUE)values this steplow, medium, highlevelspriority ← high, low
1levels <- c("low", "medium", "high")2priority <- factor(c("high", "low"), levels = levels, ordered = TRUE)3first_level <- as.character(priority[1])values this stephigh, lowprioritylow, medium, highlevelsfirst_level ← high
2priority <- factor(c("high", "low"), levels = levels, ordered = TRUE)3first_level <- as.character(priority[1])4cat(first_level, "\n", sep = "")values this stephighfirst_levelhighpriority[1]cat(first_level, " ", sep = "")
3first_level <- as.character(priority[1])4cat(first_level, "\n", sep = "")outputhighvalues this stephighfirst_level
Follow the Factor
levelsis set tolow,medium, andhigh.prioritystoreshighandlowusing those levels.- The factor is ordered, so the level order is kept with the values.
priority[1]selectshigh.as.character(priority[1])returnshigh, andcatprintshigh. | position | priority value | text afteras.character| | --- | --- | --- | | 1 | high | high | | 2 | low | low |
factor
`factor` stores category values with a fixed level set.
ordered factor
`ordered = TRUE` gives the levels a meaningful order.
as.character
`as.character` converts factor values back to text labels.
Exercise: factors.R
Reproduce the printed value high, then select the second priority value and predict the text before running it.