Frequency tables

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:

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.

songs %>% 
  count(YEAR)
   YEAR  n
1  1916  1
2  1922  1
3  1928  6
4  1929  2
5  1931  2
6  1932  2
7  1935  1
8  1936  1
9  1938  2
10 1939  3
11 1940  1
12 1941  2
13 1944  2
14 1946  2
15 1949  1
16 1950  2
17 1951  3
18 1952  1
19 1953  1
20 1954  4
21 1955  3
22 1956  9
23 1957  3
24 1958  6
25 1959 10
26 1960  5
27 1961 14
28 1962  7
29 1963 17
30 1964 27
31 1965 33
32 1966 37
33 1967 33
34 1968 39
35 1969 31
36 1970 23
37 1971 30
38 1972 27
39 1973 24
40 1974 27
41 1975 23
42 1976 18
43 1977 27
44 1978 25
45 1979 34
46 1980 25
47 1981 19
48 1982 18
49 1983 25
50 1984 22
51 1985 18
52 1986 17
53 1987 18
54 1988 15
55 1989 19
56 1990 10
57 1991 10
58 1992 14
59 1993 11
60 1994 18
61 1995 12
62 1996  7
63 1997  8
64 1998  7
65 1999 11
66 2000 12
67 2001  7
68 2002 12
69 2003 14
70 2004  9
71 2005 15
72 2006 14
73 2007 16
74 2008 19
75   NA  6
Back to top