Is possible to do a table with two group by with tbl_summary in R?



I’m working with the mtcars database, and I’m using the tbl_summary function. What I’m trying to do is to have two group by’s, first with the type of transmission and then with the number of cylinders, so I will have six columns in total for the group by’s plus the overall column, until now I have only been able to do the group by with one variable only.

This is my code:

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 %>%
    by = cyl,
    type = all_continuous() ~ "continuous2",
    statistic = list(all_continuous() ~ c("{mean} ({sd})",
                                          "{min}, {max}",
                     all_categorical() ~ "{n} / {N} ({p}%)"),
    digits = all_continuous() ~ 1,
    label = list(mpg ~ "Miles/ Gallon", disp ~ "Displacement (", 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"))


You can use the tbl_strata() function to stratify the tbl_summary() by a second by variable. Example below!


tbl <- 
  mtcars %>%
  select(am, cyl, mpg, hp) %>%
    cyl = paste(cyl, "Cylinder"),
    am = factor(am, labels = c("Automatic", "Manual"))
  ) %>%
    strata = cyl,
    ~.x %>%
        by = am,
        type = where(is.numeric) ~ "continuous"
      ) %>%
      modify_header(all_stat_cols() ~ "**{level}**")

enter image description here
Created on 2022-01-03 by the reprex package (v2.0.1)

Answered By – Daniel D. Sjoberg

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More