Open In App

How to Create a Two Way Table in R?

Last Updated : 19 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads