This is a simple shortcut to creating proportion tables in R. We’re creating a new function, ptab() that combines the functionality of the table() and prop.table() functions in base R.
We’ll use the mtcars dataset and create a table for gears and cylinders to demonstrate how to create proportion tables with the “old” (base R) and “new” (my version) methods.
To create a proportion the old way, you need the prop.table() function. prop.table() takes a table as its main argument, so you first need to create a table using the table() function:
t<-table(mtcars$cyl, mtcars$gear)
t
##
## 3 4 5
## 4 1 8 2
## 6 2 4 1
## 8 12 0 2
The next step is to pass your table into prop.table() and specify whether you want to summarize proportions by rows or columns (1 for rows, 2 for columns). We’ll summarize by columns so we can see a breakdown of cylinders by gear:
prop.table(t,2)
##
## 3 4 5
## 4 0.06666667 0.66666667 0.40000000
## 6 0.13333333 0.33333333 0.20000000
## 8 0.80000000 0.00000000 0.40000000
Now, you could combine these processess into one line and do something like this…
prop.table(table(mtcars$cyl,mtcars$gear),2)
##
## 3 4 5
## 4 0.06666667 0.66666667 0.40000000
## 6 0.13333333 0.33333333 0.20000000
## 8 0.80000000 0.00000000 0.40000000
…but it’s still ever-so-slightly annoying, so I wanted to create a better way.
The function we’re making is called ptab(), and takes three arguments: - rows: the variable you wish to display in rows - cols: the variable you wish to display in columns - by: your selection for proportion summaries by either rows or columns (1 for rows and 2 for columns)
Under the hood, well use table() to make a table of rows and columns, and prop.table() to create a proportion table out of our table:
ptab<- function(rows,columns,by){
t<<-table(rows,columns)
prop.table(t,by)
}
Let’s see how it works:
ptab(mtcars$cyl,mtcars$gear,2)
## columns
## rows 3 4 5
## 4 0.06666667 0.66666667 0.40000000
## 6 0.13333333 0.33333333 0.20000000
## 8 0.80000000 0.00000000 0.40000000
BOOM!