R / CHAPTER 04
Categories and level semantics
IntermediateTreat categories as labels with a deliberate level set.
By the end of this chapter
- Separate factor codes from labels
- Choose ordered levels explicitly
- Detect values outside the permitted categories
The idea
A factor stores integer codes together with category labels called levels. The codes describe positions in the level set, not numeric measurements. Converting a factor directly with as.numeric therefore returns codes. If numeric-looking labels represent quantities, convert their character labels deliberately and check whether parsing introduced missing values.
Define levels when a domain has a meaningful order or a fixed set of accepted categories. An ordered factor can express low before medium before high without alphabetical sorting. Values outside the supplied levels become NA, which should trigger validation if unknown categories are forbidden. Unused levels may remain after subsetting, so decide whether reports should retain empty categories or drop them.
priority <- factor(c("high","low"), levels=c("low","medium","high"), ordered=TRUE)
cat(as.integer(priority), sep=",")
cat("\n", priority[1] > priority[2], "\n", sep="")3,1 TRUE
The labels map to explicitly ordered codes three and one, making high greater than low.
Try it yourself
Validate a priority column against three permitted levels and report unknown labels.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING