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

 

table 1 data frame contingency table across multiple columns r

 

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

 

table 2 matrix contingency table across multiple columns r

 

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:

 

The YouTube video will be added soon.

 

In addition, you may have a look at the other articles on my homepage:

 

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top