The prop.table() function in R can be used to calculate the value of each cell in a table as a proportion of all values.
This function uses the following basic syntax:
prop.table(x, margin = NULL)
where:
- x: Name of the table
- margin: The margin to divide by (1 = row, 2 = column, default is NULL)
The following examples show how to use this function in practice with the following matrix in R:
#create matrix x <- matrix(1:6, nrow=2) #view matrix x [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6
Example 1: Use prop.table with margin = NULL
The following code shows how to use prop.table() without specifying a margin to divide by:
prop.table(x)
[,1] [,2] [,3]
[1,] 0.04761905 0.1428571 0.2380952
[2,] 0.09523810 0.1904762 0.2857143
The sum of all of the values in the original table is: 1 + 3 + 5 + 2 + 4 + 6 = 21.
The prop.table() function shows each individual value as a proportion of the whole.
For example:
- Cell [1, 1] = 1/21 = .0476
- Cell [1, 2] = 3/21 = .1428
- Cell [1, 3] = 5/21 = .2380
- Cell [2, 1] = 2/21 = .0952
- Cell [2, 2] = 4/21 = .1904
- Cell [3, 2] = 6/21 = .2857
Note that all of the values in the prop.table() output add up to 1.
Example 2: Use prop.table with margin = 1
The following code shows how to use prop.table() with margin=1, which divides each individual value by the row sums:
prop.table(x, margin = 1)
[,1] [,2] [,3]
[1,] 0.1111111 0.3333333 0.5555556
[2,] 0.1666667 0.3333333 0.5000000
The sum of all of the values in the first row of the original table is: 1 + 3 + 5 = 9.
The sum of all of the values in the second row of the original table is: 2 + 4 + 6 = 12.
Thus, the output shows each individual value as a proportion of the row sum.
For example:
- Cell [1, 1] = 1/9 = .1111
- Cell [1, 2] = 3/9 = .3333
- Cell [1, 3] = 5/9 = .5555
- Cell [2, 1] = 2/12 = .1667
- Cell [2, 2] = 4/12 = .3333
- Cell [3, 2] = 6/12 = .5000
Note that the values in each row of the prop.table() output add up to 1.
Example 3: Use prop.table with margin = 2
The following code shows how to use prop.table() with margin=2, which divides each individual value by the column sums:
prop.table(x, margin = 2)
[,1] [,2] [,3]
[1,] 0.3333333 0.4285714 0.4545455
[2,] 0.6666667 0.5714286 0.5454545
The sum of the values in the first column of the original table is: 1 + 2 = 3.
The sum of the values in the second column of the original table is: 3 + 4 = 7.
The sum of the values in the third column of the original table is: 5 + 6 = 11.
Thus, the output shows each individual value as a proportion of the column sum.
For example:
- Cell [1, 1] = 1/3 = .3333
- Cell [2, 1] = 2/3 = .6667
- Cell [1, 2] = 3/7 = .4285
- Cell [2, 2] = 4/7 = .5714
- Cell [1, 3] = 5/11 = .4545
- Cell [3, 3] = 6/11 = .5454
Note that the values in each column of the prop.table() output add up to 1.
Additional Resources
The following tutorials explain how to perform other common operations in R:
How to Create Frequency Tables in R
How to Create Relative Frequency Tables in R
How to Create a Contingency Table in R