How to Create a Two Way Table in R?
Last Updated :
19 Dec, 2021
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
data = matrix ( c (1:6), ncol=3)
rownames (data) = c ( 'Fruits' , 'vegetables' )
colnames (data) = c ( 'apple' , 'banana' , 'lemon' )
data = as.table (data)
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
data = data.frame (col1= c ( "apple" , "mango" , "mango" , "guava" , "apple" ),
col2= c ( "fruit" , "veg" , "fruit" , "fruit" , "veg" ))
data = table (data$col1,data$col2)
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
data = data.frame (col1= c ( "apple" , "mango" , "mango" , "guava" , "apple" ),
col2= c ( "fruit" , "veg" , "fruit" , "fruit" , "veg" ))
data = table (data$col1,data$col2)
barplot (data, main= 'Eatables' )
|
Output:
We can also display a mosaic plot.
Syntax:
mosaicplot(data)
Example: Mosaic plot visualization
R
data = data.frame (col1= c ( "apple" , "mango" , "mango" , "guava" , "apple" ),
col2= c ( "fruit" , "veg" , "fruit" , "fruit" , "veg" ))
data = table (data$col1,data$col2)
mosaicplot (data, main= 'Eatables' )
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...