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
<- read.csv("https://tinyurl.com/rta6hkbo")
polygon
# 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)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
<- with(polygon, table(revetment, pool)) %>%
prop 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?”
.1 <- with(polygon, table(revetment, pool)) %>%
propprop.table(margin = 1)
.1 prop
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?)
.2 <- with(polygon, table(revetment, pool)) %>%
propprop.table(margin = 2)
.2 prop
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.
Citation
@online{gahm2018,
author = {Gahm, Kaija},
title = {Prop.table()},
date = {2018-07-22},
url = {https://kaijagahm.github.io/posts/2018-07-22-proptable},
langid = {en}
}