如何使用stargazer并排展示分组描述统计?
问题:如何用stargazer并排展示两组描述统计?
我的数据集包含一个虚拟变量,可将数据分为两组。我希望使用stargazer并排展示两组的描述统计(如示例图所示)。以mtcars数据集为例,变量am将数据分为两组,我已通过拆分数据集为treated和control实现了上下展示统计结果,但无法实现并排展示,请问是否可行?如何实现?
已实现上下展示的代码:
treated <- mtcars[mtcars$am == 1,] control <- mtcars[mtcars$am == 0,] stargazer(treated, control, keep=c("mpg", "cyl", "disp", "hp"), header=FALSE, title="Descriptive statistics", digits=1, type="text")
解决方案
可行,你需要先手动计算两组的描述统计量,再将结果整理成适合stargazer并排展示的格式,具体步骤如下:
- 加载必要的包(未安装请先执行安装命令):
install.packages(c("dplyr", "stargazer")) library(dplyr) library(stargazer)
- 按
am分组计算描述统计并整理为宽格式:
# 计算每组的样本量、均值、标准差、极值及分位数 stats_summary <- mtcars %>% group_by(am) %>% summarise( across(c(mpg, cyl, disp, hp), list(N = ~n(), Mean = ~mean(.), SD = ~sd(.), Min = ~min(.), Pctl25 = ~quantile(., 0.25), Pctl75 = ~quantile(., 0.75), Max = ~max(.))), .groups = "drop" ) %>% # 转置并拆分变量名,整理为适合并排展示的结构 t() %>% as.data.frame() %>% rownames_to_column("Variable") %>% separate(Variable, into = c("Var", "Stat"), sep = "_") %>% pivot_wider(names_from = am, values_from = c(V1, V2)) %>% mutate( # 将两组对应统计量合并到同一列,实现并排效果 自动变速箱组 = paste(V1_0, V1_1, sep = " / "), 手动变速箱组 = paste(V2_0, V2_1, sep = " / ") ) %>% select(Var, Stat, 自动变速箱组, 手动变速箱组)
- 用stargazer输出并排统计结果:
stargazer(stats_summary, type = "text", title = "Descriptive Statistics (并排展示)", header = FALSE, digits = 1, rownames = FALSE, keep = c("Var", "Stat", "自动变速箱组", "手动变速箱组"))
如果只需要展示核心统计量(如均值±标准差),可以用简化版代码:
# 简化版:仅计算均值+标准差,直接整理为并排格式 simple_stats <- mtcars %>% group_by(am) %>% summarise(across(c(mpg, cyl, disp, hp), ~paste(round(mean(.),1), "(", round(sd(.),1), ")", sep = "")), .groups = "drop") %>% t() %>% as.data.frame() %>% rownames_to_column("Variable") stargazer(simple_stats, type = "text", title = "Descriptive Statistics (均值±标准差)", header = FALSE, digits = 1, column.labels = c("自动变速箱组(am=0)", "手动变速箱组(am=1)"), rownames = TRUE)
内容的提问来源于stack exchange,提问作者loveafter8
相关产品推荐
相关产品推荐

