R语言 如何为每个变量创建多个水平的汇总表?

raogr8fs  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(95)

我试图创建一个汇总表,就像在研究论文中看到的那样。我正在努力为表中包含的每个变量创建多个水平。
我希望我的表有4列:变量(例如性别、年龄、种族等)、水平治疗1和治疗2。
所以我希望变量列下的第一行是Sex,然后在Level列下我希望它是Male和Female。然后下一列将读取治疗1和治疗2中有多少患者是男性,等等。
我真的不知道从哪里开始,以及我是否应该在R markdown或普通脚本中这样做。
这里有一个可重复的例子,我还包括我希望最终结果看起来像什么。提前感谢!

tab <- data.frame("Sex" = c("Male", "Female", "Male", "Female"), 
                  "Treatment" = c(1,2,1, 2),
                  "Number" = c(59,43,23,20))
Variable      Levels    Treatment 1      Treatment 2 
Sex            Male         59                 23
              Female        43                 20

Age            Mean        ...                ...
                SD         ...                ...

Race           White       ...                ...
               Black       ...                ...

ETC
mzaanser

mzaanser1#

您可以使用gtsummary库来完成此操作。
首先,我们创建一个虚拟数据集进行演示。

library(tidyverse)
library(gtsummary)

# Create dummy dataset (50 cases).

set.seed(123)
df <- data.frame(
  Sex = sample(c("Female", "Male"), 50, replace = TRUE),
  Age = sample(18:80, 50, replace = TRUE),
  Race = sample(c("White", "Black"), 50, replace = TRUE),
  Income = sample(c("High", "Low"), 50, replace = TRUE),
  Treatment1 = sample(0:1, 50, replace = TRUE),
  Treatment2 = sample(0:1, 50, replace = TRUE)
)

然后我们可以使用gtsummary中的tbl_strata函数来创建一个包含所需级别的汇总表。

table <- df %>%
  tbl_strata(
  strata = c("Treatment1", "Treatment2"),
  ~ .x %>%
    tbl_summary(
      type = list(
        Age ~ "continuous",
        Sex ~ "categorical",
        Race ~ "categorical",
        Income ~ "categorical"
      ),
      statistic = list(
          Age ~ "{mean} ({sd})",
          all_categorical() ~ "{n}"
        )
    )
  )

我发现这些页面很有用:Epidemiologist R Handbook (Descriptive Tables)Stratified gtsummary Tables .
另一种方法是使用table1 package。这个例子的代码是:

df2 <- df %>%
  mutate(Sex = factor(Sex, levels = c("Male", "Female")),
         Race = factor(Race, levels = c("White", "Black")),
         Income = factor(Income, levels = c("High", "Low")),
         Treatment1 = factor(Treatment1, levels = c(0, 1)),
         Treatment2 = factor(Treatment2, levels = c(0, 1)))

units(df2$Age) <- "years"
table1(~ factor(Sex) + Age + factor(Race) + factor(Income) | Treatment1, data = df2, overall = FALSE)

table1还支持使用x*y格式的两个变量的分层,例如table1(~ factor(Sex) + Age + factor(Race) + factor(Income) | Treatment1*Treatment2)

相关问题