prop.table() function in R allows you to compute the value of each cell in a table as a proportion of:
- all values in the table
- across rows
- down columns
The function can be applied to categorical data, such as counts of different items, or numerical data, such as percentages. In other words, prop.table() can be used to determine the percentage of values in a data set equal to a certain level.
The prop.table() function is part of the stats package, so you will need to install and load the package before you can use the function. This guide will show how to use the prop.table() function in R.
Installing the stats package
install.packages('stats')
library('stats')
prop.table() syntax
prop.table(x, margin = NULL)
Arguments
- x = table or a data frame
- margin = It is optional. It can take 1 and 2 as values, where 1 stands for row-wise and 2 stands for column-wise.
Example 1: prop.table() function without margin
In this example, we will not input the margin. Therefore, the value of each cell in the table will be divided by the sum of all cells in the table.
x <- matrix(1:9, 3)
x
prop.table(x)
Output
In the table, all the values add up to: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45. In the output, each value represents the original number divided by 45. For example, Cell [1,1] = 1/45 = 0.02222222.
Example 2: prop.table() function Row-wise
In this example, we will set the margin as 1. Therefore, the value of each cell in the table will be divided by the sum of the row cells in the table.
x <- matrix(1:9, 3)
x
prop.table(x,1)
Output
In the table, the first row’s values add up to: 1 + 4 + 7 = 12. Similarly, the second and third rows’ total value is 15 and 18, respectively. In the output, each value represents the original number divided by the total of the row they belong to. For example, Cell [1,1] = 1/12 = 0.08333333 and Cell [2,3] = 8/15 = 0.5333333.
Example 3: prop.table() function Column-wise
In this example, we will set the margin as 2. Therefore, the value of each cell in the table will be divided by the sum of the column cells in the table.
x <- matrix(1:9, 3)
x
prop.table(x,1)
Output
In the table, the first column’s values add up to: 1 + 2 + 3 = 6. Similarly, the second and third columns’ total value is 15 and 24, respectively. In the output, each value represents the original number divided by the total of the column they belong to. For example, Cell [1,1] = 1/6 = 0.1666667 and Cell [3,2] = 6/15 = 0.4000000.