R Contingency Table: Create with table() Function
In R, you can use the table() function to create a contingency table. This function takes two parameters which are the variables you want to analyze the cross-tabulation of. For example, if you have a data frame df with variables sex and age, you can use the following code to generate a cross-tabulation of these two variables.
# 生成交叉表
cross_table <- table(df$sex, df$age)
# 打印交叉表
print(cross_table)
The code above will create a cross table of the variables sex and age, and save the results in the variable cross_table. If you want to save the cross table results as a data frame, you can use the as.data.frame() function to convert it into a data frame.
# 转换为数据框
cross_table_df <- as.data.frame(cross_table)
# 打印数据框
print(cross_table_df)