prop.table()

[This article was first published on woodpeckR, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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://raw.githubusercontent.com/kaijagahm/general/master/polygon_sampling_data_UMR.csv") 

# Two-way table by pool and revetment with(polygon, table(revetment, pool))

Screen Shot 2018-07-20 at 2.48.21 PM.png

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

screen-shot-2018-07-22-at-3-24-38-pm.png

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

Screen Shot 2018-07-22 at 3.26.17 PM

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

Screen Shot 2018-07-22 at 3.26.30 PM.png

Outcome

Handy function for creating proportion tables.

To leave a comment for the author, please follow the link and comment on their blog: woodpeckR.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)