Contingency Table Across Multiple Columns in R (Example)
In this R tutorial you’ll learn how to make a frequency table for multiple columns.
Table of contents:
Let’s jump right to the R code.
Creating Example Data
To start with, let’s create some example data:
set.seed(34854467) # Create example data data <- data.frame(x1 = rbinom(9, 1, 0.5), x2 = rbinom(9, 1, 0.5), x3 = rbinom(9, 1, 0.5), group = letters[1:3]) data # Print example data |
set.seed(34854467) # Create example data data <- data.frame(x1 = rbinom(9, 1, 0.5), x2 = rbinom(9, 1, 0.5), x3 = rbinom(9, 1, 0.5), group = letters[1:3]) data # Print example data
Table 1 shows the structure of our example data – It has nine rows and four columns.
Example: Create Contingency Table Across Multiple Columns
This example illustrates how to create a table with counts using multiple data frame variables.
For this task, we can use the t(), sapply(), tapply(), and sum() functions as shown below:
data_count <- t(sapply(data[ , 1:3], # Create contingency table function(x) tapply(x, data[ , 4], sum))) data_count # Print contingency table |
data_count <- t(sapply(data[ , 1:3], # Create contingency table function(x) tapply(x, data[ , 4], sum))) data_count # Print contingency table
As shown in Table 2, we have created a table with contingencies across several variables with the previous syntax.
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. I’m explaining the R programming code of this article in the video:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may have a look at the other articles on my homepage:
- Split Data Frame Variable into Multiple Columns
- Summarize Multiple Columns of data.table by Group
- Remove Multiple Columns from data.table
- Paste Multiple Columns Together in R
- Sum Across Multiple Rows & Columns Using dplyr Package
- R Programming Examples
In this tutorial you have learned how to make a frequency table for multiple variables in R. Don’t hesitate to let me know in the comments section, in case you have additional questions. Furthermore, please subscribe to my email newsletter to receive updates on the newest tutorials.
Statistics Globe Newsletter