table & prop.table

Basics

table is a function used to build a contingency table, which is a table that shows counts for categorical data, from one or more categories. prop.table is a function that accepts table output, returning proportions of the counts.


Examples

How do I get the count of students by year in our grades data.frame?

Click to see solution
table(grades$year)
freshman    junior    senior sophomore
       1         4         2         3

How do I get the percentages of students in each year?

Click to see solution
prop.table(table(grades$year))
freshman    junior    senior sophomore
     0.1       0.4       0.2       0.3

How do I get a count of students in each grade broken down by sex?

Click to see solution
table(grades$year, grades$sex)
          F M
freshman  0 1
junior    2 2
senior    1 1
sophomore 1 2

How do I get the percentages of students in each grade broken down by sex?

Click to see solution
prop.table(table(grades$year, grades$sex))
            F   M
freshman  0.0 0.1
junior    0.2 0.2
senior    0.1 0.1
sophomore 0.1 0.2