A three-way table is a type of table that displays the frequencies for three categorical variables.
The easiest way to create a three-way table in R is to use the xtabs() function:
three_way <- xtabs(~ var1 + var2 + var3, data=df)
If you’d like to view the three-way table in a more compact manner, you can use the ftable() function:
three_way_ftable <- ftable(three_way)
Note: Both the xtabs() and ftable() functions are built into base R.
The following example shows how to use these functions to create three-way tables in R in practice.
Example: How to Create Three-Way Tables in R
Suppose we have the following data frame that contains information about various basketball players:
#create data frame df <- data.frame(team=c('A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'), position=c('G', 'G', 'G', 'F', 'F', 'G', 'G', 'F', 'F', 'F'), starter=c('Yes', 'No', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'No'), points=c(30, 28, 24, 24, 28, 14, 16, 20, 34, 29)) #view data frame df team position starter points 1 A G Yes 30 2 A G No 28 3 A G No 24 4 A F Yes 24 5 A F No 28 6 B G Yes 14 7 B G No 16 8 B F Yes 20 9 B F Yes 34 10 B F No 29
Suppose we would like to create a three-way table to view the frequency of players based on three variables: team, position, and starter.
We can use the xtabs() function to create this three-way table:
#create three-way table three_way <- xtabs(~ team + position + starter, data=df) #view three-way table three_way , , starter = No position team F G A 1 2 B 1 1 , , starter = Yes position team F G A 1 1 B 2 1
The first table in the output shows the frequency of players by team and position where the starter variable is equal to No.
The second table shows the frequency of players by team and position where the starter variable is equal to Yes.
If we’d like, we can use the ftable() function to “flatten” these tables into one table:
#convert table to ftable three_way_ftable <- ftable(three_way) #view ftable three_way_ftable starter No Yes team position A F 1 1 G 2 1 B F 1 2 G 1 1
The resulting three-way table shows the frequencies of all three variables in a “flat” format.
For example, we can see:
- There was 1 player who was on team A, position F, and was not a starter.
- There was 1 player who was on team A, position F, and was a starter.
- There were 2 players who were on team A, position G, and were not starters.
And so on.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Create a Two Way Table in R
How to Create a Frequency Table by Group in R
How to Plot a Table in R