Calculating tables of proportions
The margins of a table (the row totals or the column totals) are often useful for calculating proportions instead of counts. Here is a data matrix called counts:
counts<-matrix(c(2,2,4,3,1,4,2,0,1,5,3,3),nrow=4)
counts
[,1] [,2] [,3]
[1,] 2 1 1
[2,] 2 4 5
[3,] 4 2 3
[4,] 3 0 3
The proportions will be different when they are expressed as a fraction of the row totals or as a fraction of the column totals. You need to remember that the row subscripts come first, which is why margin number 1 refers to the row totals:
prop.table(counts,1)
[,1] [,2] [,3]
[1,] 0.5000000 0.2500000 0.2500000
[2,] 0.1818182 0.3636364 0.4545455
[3,] 0.4444444 0.2222222 0.3333333
[4,] 0.5000000 0.0000000 0.5000000
The column totals are the second margin, so to express the counts as proportions of the relevant column total use:
prop.table(counts,2)
[,1] [,2] [,3]
[1,] 0.1818182 0.1428571 0.08333333
[2,] 0.1818182 0.5714286 0.41666667
[3,] 0.3636364 0.2857143 0.25000000
[4,] 0.2727273 0.0000000 0.25000000
To check that the column proportions sum to one, use colSums like this:
colSums(prop.table(counts,2))
[1] 1 1 1
If you want the proportions expressed as a fraction of the grand total sum(counts), then simply omit the margin number:
prop.table(counts) [,1] [,2] [,3] [1,] 0.06666667 0.03333333 0.03333333 [2,] 0.06666667 0.13333333 0.16666667 [3,] 0.13333333 0.06666667 0.10000000 [4,] 0.10000000 0.00000000 0.10000000 sum(prop.table(counts)) [1] 1
In any particular case, ...
Get The R Book now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.