9 R Lists and Factors
This chapter covers
- Working with lists: creating, modifying, and accessing data from them
- Writing our own functions that either create list output, use a list as input, or both
- Using factors successfully though inspection and transformation with base R functions and functions from the forcats package
- Creating ggplot bar charts that make the best use of factor variables
When working in R long enough, you’ll encounter list objects again and again. You may bump into factors every now are again but try to side-step their use. However, these are very important and useful data structures and we ought to fully understand them. This chapter goes over lists, which we’ve seen before, in much more detail. We’ll understand how to better create lists, how to access data from them, how to combine lists together, and how to go to and from lists and data frames. Factors will be introduced in the second part of this chapter. They shouldn’t be something to be avoided as they are genuinely useful, especially in the context of plotting data with ggplot.
We’ll use a dataset called german_cities (available in the edr package) to work through examples that involve factors, eventually getting to nicer and nicer plots. The functions that we’ll use throughout this chapter will be an even mix of base R functions and functions that are available in the Tidyverse packages forcats and ggplot.