是否可以在 R 中使用 tbl_summary 制作一个包含两个 group by 的表?

Beg*_*dev 8 r gtsummary

我正在使用 mtcars 数据库,并且使用 tbl_summary 函数。我想做的是有两个分组依据,首先是变速箱类型,然后是气缸数量,所以我总共有六列分组依据加上整个列,到目前为止我只有能够仅使用一个变量进行分组。

这是我的代码:

mtcars2 <- within(mtcars, {
  vs <- factor(vs, labels = c("V", "S"))
  am <- factor(am, labels = c("Automatic", "Manual"))
  cyl  <- ordered(cyl)
  gear <- ordered(gear)
  carb <- ordered(carb)
})

mtcars2 %>%
  tbl_summary(
    by = cyl,
    type = all_continuous() ~ "continuous2",
    statistic = list(all_continuous() ~ c("{mean} ({sd})",
                                          "{min}, {max}",
                                          "{skew}"),
                     all_categorical() ~ "{n} / {N} ({p}%)"),
    digits = all_continuous() ~ 1,
    label = list(mpg ~ "Miles/ Gallon", disp ~ "Displacement (cu.in.)", hp ~ "Gross Horsepower", drat ~ "Rear Axle Ratio", wt ~ "Weight (1,000 lbs)", qsec ~ "1/4 Mile Time", vs ~ "Engine (Shape)", am ~ "Transmission", gear ~ "No. of Forward Gears", carb ~ "No. of Carburetors")
  ) %>%
  add_overall() %>%
  modify_header(label ~ "**Variable**") %>%
  modify_spanning_header(c("stat_1", "stat_2", "stat_3") ~ "**Number of Cylinders**") %>%
  modify_caption("**Table 1. Descriptive Statistics**")  %>%
  add_stat_label(label = all_continuous() ~ c("Mean (SD)", "Range", "Skew"))
Run Code Online (Sandbox Code Playgroud)

Dan*_*erg 14

您可以使用该函数按变量按秒tbl_strata()进行分层。tbl_summary()下面举例!

library(gtsummary)

tbl <- 
  mtcars %>%
  select(am, cyl, mpg, hp) %>%
  dplyr::mutate(
    cyl = paste(cyl, "Cylinder"),
    am = factor(am, labels = c("Automatic", "Manual"))
  ) %>%
  tbl_strata(
    strata = cyl,
    ~.x %>%
      tbl_summary(
        by = am,
        type = where(is.numeric) ~ "continuous"
      ) %>%
      modify_header(all_stat_cols() ~ "**{level}**")
  )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 由reprex 包于 2022 年 1 月 3 日创建(v2.0.1)