How to generate a two-way contingency table in R language?

In R language, you can create a two-dimensional contingency table using the table() function. Start by splitting the data into two variables, and then pass these two variables as parameters to the table() function.

Here is a simple example:

# 创建两个变量:性别和学历
gender <- c("男", "女", "女", "男", "男", "女", "男", "女")
education <- c("硕士", "本科", "本科", "硕士", "博士", "硕士", "博士", "硕士")

# 生成二维列联表
table(gender, education)

The output result is:

     education
gender  本科 博士 硕士
   女      1   0   2
   男      1   1   2

This two-way contingency table displays the relationship between gender and education level. In this example, there is one woman and one man with a bachelor’s degree, two women and two men with a master’s degree, and only one man with a doctorate.

I hope this example helps you!

bannerAds