How to Create a Three Way Table in R
Last Updated :
24 Apr, 2025
A three-way table, also known as a three-dimensional contingency table, is a tabular representation of the joint frequencies of three categorical variables. It provides a way to analyze the relationships between three categorical variables simultaneously. In this article, we will study different approaches by which we can create a three-way table in R Programming Language.
Ways to Create a Three-Way Table in R
Below are some of the ways by which we can create a three-way table in R
- Using the f
table()
Function - Using the
xtabs()
Function - Using the
table()
Using table() with Array Indexing - Using Nested
for
Loops
Create Three-Way Tables in R using ftable()
Syntax
In R, We can create a three-way table by using the ftable() function:
three_way_ftable <- ftable(three_way)
R
# Generate example data
set.seed(123) # for reproducibility
# Create a data frame with sample data
data <- data.frame(
Subject = sample(c("Math", "Science", "English"), 100, replace = TRUE),
Gender = sample(c("Male", "Female"), 100, replace = TRUE),
Performance = sample(c("High", "Medium", "Low"), 100, replace = TRUE)
)
head(data)
# Create a three-way table using the table() function
three_way_table <- ftable(data$Subject, data$Gender, data$Performance)
# Display the table
print(three_way_table)
Output:
Subject Gender Performance
1 English Male Medium
2 English Female High
3 English Female High
4 Science Male Medium
5 English Male Low
6 Science Male High High Low Medium
English Female 11 5 2
Male 6 6 5
Math Female 8 3 6
Male 9 2 5
Science Female 10 2 9
Male 3 2 6
In this method, we utilize the ftable()
function in R to create a three-way table. We start by passing the variables of interest (e.g., Subject, Gender, Performance) into the ftable()
function. Internally, the function identifies unique combinations of levels for each variable and computes the frequencies of these combinations.Finally ,the resulting table displays the frequencies of occurrences for each combination of categories.
Create Three-Way Tables in R using xstabs()
In R,we can create a three-way table by using the xtabs() function
Syntax
three_way <- xtabs(~ var1 + var2 + var3, data=df)
R
# Generate example data
set.seed(123) # for reproducibility
# Create a data frame with sample data
exam_data <- data.frame(
Year = sample(c("Freshman", "Sophomore", "Junior"), 200, replace = TRUE),
Study_Method = sample(c("Self-Study", "Group Study"), 200, replace = TRUE),
Result = sample(c("Pass", "Fail"), 200, replace = TRUE)
)
head(exam_data)
# Create a three-way contingency table using xtabs()
three_way_table_xtabs <- xtabs(~ Year + Study_Method + Result, data = exam_data)
# Display the table
print(three_way_table_xtabs)
Output:
Year Study_Method Result
1 Junior Group Study Fail
2 Junior Self-Study Pass
3 Junior Group Study Pass
4 Sophomore Self-Study Fail
5 Junior Group Study Fail
6 Sophomore Self-Study Pass, , Result = Fail Study_Method
Year Group Study Self-Study
Freshman 15 19
Junior 17 21
Sophomore 17 20, , Result = Pass Study_Method
Year Group Study Self-Study
Freshman 15 14
Junior 8 21
Sophomore 15 18
In this method, we use the xtabs()
function to construct a three-way table. We specify the formula ~ var1 + var2 + var3
to indicate the three categorical variables of interest (e.g., Year, Study_Method, Result). The xtabs()
function then cross-tabulates these variables to generate a contingency table, where the rows and columns correspond to the levels of each variable. The resulting table displays the frequencies of occurrences for each combination of categories.
Create Three-Way Tables in R using table() with Array Indexing
In R,we can create a three-way table by using table() with Array Indexing
Syntax
three_way_table <- table(var1, var2, var3, data = your_data_frame)
R
# Example data
data <- data.frame(
Gender = c("Male", "Female", "Male", "Male", "Female", "Female"),
AgeGroup = c("Young", "Young", "Old", "Old", "Young", "Old"),
Region = c("East", "West", "West", "East", "East", "West")
)
data
# Creating a three-way table
three_way_table <- table(data$Gender, data$AgeGroup, data$Region)
# Print the table
print(three_way_table)
Output:
Gender AgeGroup Region
1 Male Young East
2 Female Young West
3 Male Old West
4 Male Old East
5 Female Young East
6 Female Old West, , = East
Old Young
Female 0 1
Male 1 1, , = West
Old Young
Female 1 1
Male 1 0
In this method, we use the table()
function with array indexing to create a three-way table. The table()
function computes the frequency of each combination of levels from the three categorical variables: Gender
, AgeGroup
, and Region
. By specifying the three variables as arguments to the table()
function, we obtain a three-dimensional array representing the joint frequencies. Each dimension of the array corresponds to a variable, and the entries in the array represent the frequency of each combination of levels.
Create Three-Way Tables in R using Nested for Loops
R
# Example data
data <- data.frame(
Gender = c("Male", "Female", "Male", "Male", "Female", "Female"),
AgeGroup = c("Young", "Young", "Old", "Old", "Young", "Old"),
Region = c("East", "West", "West", "East", "East", "West")
)
data
# Unique levels of variables
genders <- unique(data$Gender)
age_groups <- unique(data$AgeGroup)
regions <- unique(data$Region)
# Initialize an empty table
three_way_table <- array(0, dim = c(length(genders),length(age_groups),length(regions)))
# Fill in the table
for (i in 1:length(genders)) {
for (j in 1:length(age_groups)) {
for (k in 1:length(regions)) {
three_way_table[i, j, k] <- sum(data$Gender == genders[i] &
data$AgeGroup == age_groups[j] &
data$Region == regions[k])
}
}
}
# Print the table
print(three_way_table)
Output:
Gender AgeGroup Region
1 Male Young East
2 Female Young West
3 Male Old West
4 Male Old East
5 Female Young East
6 Female Old West, , 1 [,1] [,2]
[1,] 1 1
[2,] 1 0, , 2 [,1] [,2]
[1,] 0 1
[2,] 1 1
In this method, we create a three-way table using nested for
loops. We first identify the unique levels of each categorical variable (Gender
, AgeGroup
, Region
). Then, we initialize an empty three-dimensional array to store the frequencies of each combination of levels. We iterate over each combination of levels using nested loops and calculate the frequency of each combination by counting the occurrences in the original data frame (data
). Finally, we populate the three-way table with the calculated frequencies.
Conclusion
In this article we understood that creating a three-way table in R is a straightforward process that allows for the comprehensive analysis of relationships between three categorical variables. Through the utilization of functions like table() or xtabs(), R enables users to efficiently generate contingency tables summarizing the joint distribution of these variables.
Similar Reads
How to Create a Two Way Table in R?
In this article, we will create a two-way table in R programming language. A two-way table is used to display frequency for two categorical variables. The rows represent the categorical features and the column represents frequency. We can create two-way table using as.table() method. as.table() func
2 min read
How to Create Tables in R?
In this article, we will discuss how to create tables in R Programming Language. Method 1: Create a table from scratch We can create a table by using as.table() function, first we create a table using matrix and then assign it to this method to get the table format. Syntax: as.table(data) Example: I
2 min read
How to Create Pivot Tables in R?
In this article, we will discuss how to create the pivot table in the R Programming Language. The Pivot table is one of Microsoft Excel's most powerful features that let us extract the significance from a large and detailed data set. A Pivot Table often shows some statistical value about the dataset
2 min read
How to Perform a Three-Way ANOVA in R
Analysis of Variance (ANOVA) is a powerful statistical technique used to compare means across multiple groups. A Three-Way ANOVA extends this analysis to investigate the interaction effects between three categorical variables on a continuous outcome variable. In this detailed guide, we will walk thr
5 min read
How to Create Summary Tables in R?
In this article, we will discuss how to create summary tables in R Programming Language. The summary table contains the following information: vars: represents the column numbern: represents the number of valid casesmean: represents the mean valuemedian: represents the median valuetrimmed: represent
4 min read
How to create a matrix in R
In this article, we will discuss What is a matrix and various methods to create a matrix by using R Programming Language. What is a matrix?A matrix is a two-dimensional data set that collects rows and columns. The matrix stores the data in rows and columns format. It is possible to access the data i
3 min read
How to Create Radar Charts in R?
In this article, we are going to see how to create Radar Charts in R Programming Language. Radar charts are also known as Spider or Web or Polar charts. It is a graphical graph to display multivariate data in form of 2D charts of three or more quantitative variables which are represented on axes sta
4 min read
How to Create a Power PivotTable in Excel?
When we have to compare the data (such as name/product/items, etc.) between any of the columns in excel then we can easily do with the help of Pivot table and pivot charts. But it fails when it comes to comparing those data which are in two different datasets, at that time Power Pivot comes into rol
4 min read
How to Create a Two-Variable Data Table in Excel?
Two-Variable Data Table is a very significant tool for what-if data analysis. With the help of two-variable data tables, we can find all possible trends that can arrive by changing different values. For example, if we know the annual sales of a company, its percentage of expenses and growth. So, by
2 min read
How to Address data.table Error in R
The data. table package in R Programming Language provides a fast and concise syntax for data manipulation tasks, making it a favorite among data scientists and analysts. With its rich set of functions, it allows for seamless data aggregation, filtering, and computation. In this article, we will exp
3 min read