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 = "")
  1. levels ← low, medium, high

    1levels <- c("low", "medium", "high")2priority <- factor(c("high", "low"), levels = levels, ordered = TRUE)
    values this steplow, medium, highlevels
  2. priority ← 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, highlevels
  3. first_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]
  4. cat(first_level, " ", sep = "")

    3first_level <- as.character(priority[1])4cat(first_level, "\n", sep = "")
    outputhigh
    values this stephighfirst_level

Follow the Factor

  1. levels is set to low, medium, and high.
  2. priority stores high and low using those levels.
  3. The factor is ordered, so the level order is kept with the values.
  4. priority[1] selects high.
  5. as.character(priority[1]) returns high, and cat prints high. | position | priority value | text after as.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.