The Wayback Machine - https://web.archive.org/web/20231204220401/https://www.geeksforgeeks.org/how-to-create-a-two-way-table-in-r/
Open In App
Related Articles

How to Create a Two Way Table in R?

Improve Article
Improve
Save Article
Save
Like Article
Like

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() function in R Language is used to convert an object into a table.

Syntax: 

as.table(x)

Parameters:

x: Object to be converted

Create a Two Way Table from matrix

Here we are going to create a table from matrix.

Example: Table from Matrix

R




# create matrix with 3 columns
data = matrix(c(1:6), ncol=3)
  
# specify row and column names 
rownames(data) = c('Fruits', 'vegetables')
colnames(data) = c('apple', 'banana', 'lemon')
  
# convert matrix to table
data = as.table(data)
  
# display 
data


Output:

Create a Two Way Table from Dataframe

We are going to use table() method to create two-way table from the dataframe.

Syntax;

table(df$column1, df$column2,...,df$column n)

where, df is the input dataframe

Example: Table from Dataframe

R




# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"), 
                  col2=c("fruit","veg","fruit","fruit","veg"))
  
  
# convert dataframe to table
data = table(data$col1,data$col2)
  
# display 
data


Output:

Visualizing two way table

We can see the bar graph for the two-way table using barplot() function

Syntax:

barplot(data)

where, data is the input dataframe

Example: Barplot visualization

R




# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"), 
                  col2=c("fruit","veg","fruit","fruit","veg"))
  
# convert dataframe to table
data = table(data$col1,data$col2)
  
# display  barplot
barplot(data, main='Eatables')


Output:

We can also display a mosaic plot.

Syntax:

mosaicplot(data)

Example: Mosaic plot visualization 

R




# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"), 
                  col2=c("fruit","veg","fruit","fruit","veg"))
  
# convert dataframe to table
data = table(data$col1,data$col2)
  
# display mosaicplot
mosaicplot(data, main='Eatables')


Output:


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 19 Dec, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials