在R中将循环生成的多个交叉表按列合并为单个表格
问题
我通过循环能给数据框的列生成多个交叉表,但现在这些表是逐个输出的。因为所有交叉表行数一致,我想把它们像cbind()那样按列合并成一个表格。
示例数据
test1 <- structure(list(weight = c(0.2158, 0.799, 0.611, 0.4969, 0.3469, 1.0107, 0.6946, 0.9415, 1.4008, 0.6192), Q2_1 = structure(c(4, 4, 2, 2, 3, 3, 3, 2, 3, 2), label = "How worried, if at all, are you about each of the following? - You or someone in your family will get sick with COVID-19", format.spss = "F40.0", display_width = 5L, labels = c(Skipped = -1, `Very worried` = 1, `Somewhat worried` = 2, `Not too worried` = 3, `Not at all worried` = 4), class = c("haven_labelled", "vctrs_vctr", "double")), Q2_2 = structure(c(3, 4, 2, 4, 3, 3, 4, 2, 3, 4), label = "How worried, if at all, are you about each of the following? - You might experience serious side effects from the COVID-19 vaccine", format.spss = "F40.0", display_width = 5L, labels = c(Skipped = -1, `Very worried` = 1, `Somewhat worried` = 2, `Not too worried` = 3, `Not at all worried` = 4), class = c("haven_labelled", "vctrs_vctr", "double")), group = c("E", "E", "E", "D", "E", "E", "D", "E", "D", "E")), row.names = c(NA, -10L), class = "data.frame")
现有循环代码(逐个输出交叉表)
library(pollster) library(rlang) for (i in colnames(test1)[2:3]) { table <- crosstab( df = test1, x = !!sym(i), y = group, weight = weight, pct_type = "column") print(table) }
预期输出
D E D E <chr> <dbl> <dbl> <dbl> <dbl> 1 Somewhat worried 19.2 47.8 0 34.2 2 Not too worried 80.8 29.9 54.0 34.6 3 Not at all worried 0 22.3 46.0 31.2 4 n 2.59 4.54 2.59 4.54
解决方案
可以先创建空列表存储每个循环生成的交叉表,再通过dplyr::bind_cols()合并列表内的表格,同时去掉重复的分类列。
修改后的代码如下:
library(pollster) library(rlang) library(dplyr) # 创建空列表用于存储交叉表 table_list <- list() for (i in colnames(test1)[2:3]) { # 生成单个交叉表 tab <- crosstab( df = test1, x = !!sym(i), y = group, weight = weight, pct_type = "column") # 将交叉表加入列表 table_list[[i]] <- tab } # 合并表格:保留第一个表的分类列,后续表仅取数值列 combined_table <- table_list[[1]] %>% bind_cols(lapply(table_list[-1], function(x) select(x, -1))) # 查看合并结果 print(combined_table)
代码说明
- 存储交叉表:用列表
table_list收集所有循环生成的交叉表,避免逐个打印输出。 - 合并逻辑:合并时保留第一个表的完整列(含分类列),后续表格仅选取数值列,避免出现重复的分类列。
- 输出结果:合并后的表格与预期输出结构完全一致。
内容的提问来源于stack exchange,提问作者Laura
相关产品推荐
相关产品推荐

