Conclusion
By completing this module, you’ve built a solid understanding of R’s tool for representing categorical data: factors.
Hand-In Assignment
Factors Capstone Assignment
Complete each step below in your own R session, then submit your work (see “What to Hand In” below).
- Generate. Create a character vector called
sizescontaining 15 values randomly sampled (with replacement) from{"small", "medium", "large"}. Then create a factor calledsize_factorfromsizes. - Inspect. Print
levels(size_factor)andtable(size_factor). In a comment, explain what each of these two commands tells you. - Modify levels. Relabel the factor’s levels to
{"S", "M", "L"}(in the order that matches your original{"small", "medium", "large"}levels). - Conceptual explanation. In a comment, explain what would happen if you ran
size_factor + 1, and why, referring specifically to what a factor actually stores internally. - Use-case reasoning. In a comment, describe one variable from a dataset you’re familiar with (real or hypothetical) that should be represented as a factor, and one that should not, and explain your reasoning for each.
What to Hand In
Save all of your commands, in the order you ran them, in a single plain-text or R script file (e.g. yourname_factors.R), including all four required comments.
A teacher reviewing your submission should be able to see: a correctly constructed factor, correct use of levels() and table() with an accurate explanation, correct level relabeling, an accurate conceptual explanation of factor arithmetic, and sound reasoning about when a factor is (and isn’t) the right choice.
Learning Goals
Now that you’ve completed this module, you should be able to:
- Describe the characteristics of an R factor.
- Explain how factors differ from atomic vectors.
- Generate new factors in R.
- Access and modify factor levels.
- Describe important use-cases for Factors, and explain why factors are the best choice in these situations.
Additional Reading
For more information on the topics we’ve covered in this module, the following chapter from Hadley Wickham’s R for Data Science is an excellent resource.
- Factors in the Second Edition.
Advanced Reading
For a much more technical deep-dive into vectors and vector-like structures (including factors), check out the following chapter from Hadley Wickham’s Advanced R.
Next Steps
Now that you have a good introduction to the fundamental data structures of the R statistical programming language you’re ready to start thinking about how to best organize your data analysis projects. In the next module, we’ll explore different aspects of effective R workflows, scripts, working directories, R projects, file paths, and coding style, to help you create reproducible, organized, and efficient data analysis projects.