【发布时间】:2021-03-12 17:36:09
【问题描述】:
我正在寻找一种简单的方法来创建具有两个变量的多变量交叉表,该变量仅显示平均值、标准偏差和频率/样本大小第三个变量。最好的情况是列总和和行总和。
以 mtcars 数据集为例(带有“cyl”和“vs”的表格;“hp”的平均值、标准差和频率):
在 Stata 中,它将是 tabulate cyl vs, summarize(hp) freq mean sta。
To make clear how it ideally should look like I've made an example (the results are just made up):
或
Example 2 (results also just made up)
(最后我必须将表格转移到 LaTeX - 最好是使用 stargazer - 所以如果这可能的话,那将是最好的。)
我发现了很多带有均值的交叉表的解决方案,但仅适用于两个变量。当然不是平均,标准。开发。和频率在一张表中。你会对我有很大的帮助。
编辑:现在我试过了,但我不知道如何添加标准差、列总和和行总和。
library(tidyr)
ct <- mtcars %>%
group_by(cyl, vs) %>%
summarise(hp = mean(hp, na.rm=TRUE), .groups = "drop") %>%
spread(vs, hp)
ct
ct %>%
adorn_rounding() %>%
adorn_ns(
ns = mtcars %>% # calculate the Ns on the fly by calling tabyl on the original data
tabyl(cyl, vs)
) %>%
adorn_title("combined", row_name = "Cylinders", col_name = "Is Automatic")
# stargazer(ct)
我得到了这个(通过括号中的组和频率表示):
Cylinders/Is Automatic 0 1
1 4 91 (1) 81.8 (10)
2 6 131.7 (3) 115.2 (4)
3 8 209.2 (14) NA (0)
编辑2:
library(tidyr)
library(arsenal)
tab1 <- tableby(vs ~ hp, data=mtcars, strata = cyl, numeric.stats = c("meansd", "N"), test = FALSE)
summary(tab1, text = TRUE)
这对我来说很有效,但是为了将准确的表格(如我的插图中的表格)导入 LaTeX,很遗憾,我必须手动做很多工作。
不幸的是,stargazer(tab1) 根本不起作用,因为
% 错误:无法识别的对象类型。
.
summary(tab1, text = "latex") 确实有效,但如前所述,要在 LaTeX 中获得或多或少漂亮的出版质量表,需要大量手工工作。
可能问的太多了,但是有人有什么想法吗?
【问题讨论】: