How to use prop.table() in R

The prop.table() in R can be used to calculate the value of each cell in a (contingency) table as a proportion of all values.

The function uses the following basic syntax:

prop.table( x, margin=NULL)

where:

Example:

create a matrix

x <- matrix (1:6, nrow = 2)

view matrix

##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6

1. Use prop.table() with margin = NULL

prop.table (x)
##            [,1]      [,2]      [,3]
## [1,] 0.04761905 0.1428571 0.2380952
## [2,] 0.09523810 0.1904762 0.2857143

The sum of all the values in the original table is:

sum(1:6)
## [1] 21

The prop.table() function shows each individual value as a proportion of the whole.

–> (divide each value by the sum of them)

For example:

  • cell [1,1] = 1 / 21 = 0.0476

  • cell [2,3] = 6 / 21 = 0.2857

Note that all the values in the prop.table() output add up to 1.

2. Use prop.table() with margin = 1

prop.table (x, margin = 1)
##           [,1]      [,2]      [,3]
## [1,] 0.1111111 0.3333333 0.5555556
## [2,] 0.1666667 0.3333333 0.5000000

Here, each value is divided by the row sums

e.g.:
The sum of 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 = 0.1111

  • cell [2,3] = 6 / 12 = 0.5

NOTE: all the values in each row of this prop.table() output add up to 1.

3. Use prop.table() with margin = 2

prop.table (x, margin = 2)
##           [,1]      [,2]      [,3]
## [1,] 0.3333333 0.4285714 0.4545455
## [2,] 0.6666667 0.5714286 0.5454545

Here, each value is divided by the column sums

e.g.:
The sum of the first column of the original table is: 1 + 2 = 3.
The sum of the second column of the original table is 2 + 4 = 7.
The sum of the second column of the original table is 5 + 6 = 11.

Therefore, the output shows each individual value as a proportion of the column sum.

For example:

  • cell [1,1] = 1 / 3 = 0.3333

  • cell [2,1] = 3 / 7 = 0.4285

  • cell [2,3] = 6 / 11 = 0.5454

NOTE: all the values in each column of this prop.table() output add up to 1.

How to use margin.table() in R

margin.table(x)
## [1] 21

Where the sum of all values (cells) in this table is exactly 21, so we can conclude that it is the sum of table entries.

Similarly, we can compute the rowsum or the columnsum of the table, for example:

margin.table (x, margin = 1) # this computes the row sum
## [1]  9 12
margin.table (x, margin = 2) # this computes the sum of each column
## [1]  3  7 11