How to Make a Two-way Contingency Table in R (Example Code)

In this article you’ll learn how to create a contingency table in R programming.

Creation of Example Data

my_df <- data.frame(var_a = c("x", "y", "x", "z", "y", "y"),  # Construct data frame in R
                    var_b = c("a", "b"))
my_df                                                         # Display example data in RStudio console
#   var_a var_b
# 1     x     a
# 2     y     b
# 3     x     a
# 4     z     b
# 5     y     a
# 6     y     b

Example: How to Make a Two-way Contingency Table Using the table() Function

table(my_df)                                                  # Create two-way contingency table
#      var_b
# var_a a b
#     x 2 0
#     y 1 2
#     z 0 1

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top