July 22, 2018

(This article was first published on woodpeckR, and kindly contributed to R-bloggers)


How can I convert a frequency table into proportions?


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("") 

# 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?


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

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


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)

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)

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


Handy function for creating proportion tables.

To leave a comment for the author, please follow the link and comment on their blog: woodpeckR. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


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)