The tidyverse provides the count() function, a clean and expressive way to produce frequency tables. It takes a data frame and a variable, and returns a tibble with the variable’s values and their frequencies.
library(dplyr)songs %>%count(THEME)
THEME n
1 Heartbreak 145
2 Life_and_death 131
3 Love 139
4 Party_songs 162
5 People_and_places 145
6 Politics_and_protest 141
7 Sex 131
8 <NA> 6
This gives a simple table with two columns:
the category (e.g., levels of education)
the number of cases in each category
If you want the categories sorted from most to least frequent, you can add:
songs %>%count(THEME, sort =TRUE)
THEME n
1 Party_songs 162
2 Heartbreak 145
3 People_and_places 145
4 Politics_and_protest 141
5 Love 139
6 Life_and_death 131
7 Sex 131
8 <NA> 6
This replaces sort(table(x)) with a single tidy and readable expression.
Practice
Make a frequency table for the variable YEAR with dplyr.
NOTE: The songs dataset and the dplyr package are already loaded in the working directory of this webr session.