prop.table()

Making a frequency table with proportions instead of counts. Preview image from https://twitter.com/lyric_rep/status/1010594530435846144.

Kaija Gahm true
07-22-2018

This post has been slightly modified from its original form on woodpeckR.

Problem

How can I convert a frequency table into proportions?

Context

This is a continuation of the data manipulation discussed in the with() post. I had just finished making a table

# Load data from GitHub
polygon <- read.csv("https://tinyurl.com/rta6hkbo")

# Two-way table by pool and revetment
with(polygon, table(revetment, pool))
         pool
revetment   4   8  13
        0  71 199 103
        1  57  53  44

What if I want to see this table broken down by proportion of polygons, not counts?

Solution

The prop.table() function will do this nicely.

library(dplyr)

prop <- with(polygon, table(revetment, pool)) %>% 
  prop.table()

prop
         pool
revetment          4          8         13
        0 0.13472486 0.37760911 0.19544592
        1 0.10815939 0.10056926 0.08349146

By default, the proportions are calculated over the entire table. So each cell represents the proportion of all polygons that are in that pool with that value of revetment. The whole table sums to 1.

If you want proportions across rows or down columns, all you need to do is add the margin = argument.

margin = 1 sums across rows. Each row sums to 1. This would answer the question, “What proportion of the polygons [with, or without] revetment are located in each of the three pools?”

prop.1 <- with(polygon, table(revetment, pool)) %>% 
  prop.table(margin = 1)

prop.1
         pool
revetment         4         8        13
        0 0.1903485 0.5335121 0.2761394
        1 0.3701299 0.3441558 0.2857143

margin = 2 sums down columns. Each column sums to 1. This would answer the question, "What proportion of the polygons in [pool] have revetment? (or, what proportion don’t have revetment?)

prop.2 <- with(polygon, table(revetment, pool)) %>% 
  prop.table(margin = 2)

prop.2
         pool
revetment         4         8        13
        0 0.5546875 0.7896825 0.7006803
        1 0.4453125 0.2103175 0.2993197

Outcome

Handy function for creating proportion tables.

Corrections

If you see mistakes or want to suggest changes, please create an issue on the source repository.

Citation

For attribution, please cite this work as

Gahm (2018, July 22). Kaija Gahm: prop.table(). Retrieved from https://kaijagahm.netlify.app/posts/2018-07-22-proptable/

BibTeX citation

@misc{gahm2018prop.table(),
  author = {Gahm, Kaija},
  title = {Kaija Gahm: prop.table()},
  url = {https://kaijagahm.netlify.app/posts/2018-07-22-proptable/},
  year = {2018}
}