rdplyrtidyrplyrfrequency-distribution

r nested table with row percents


I am trying to create a nested table in R with Row Percents.

This is my dataset:

data("mtcars")
head(mtcars)

I am trying to create a summary table like this:

                vs = 0                             vs=1
         am =0         am-1                am =0        am-1
 Gear=3  12(100%)      0(0%)               3(100%)      0(0%)
 Gear=4  0(0%)         2(100%)             4(40%)       6(60%)
 Gear=5  0(0%)         4(100%)             0(0%)        1(100%)

I am not sure how. I tried this:

  ftable(mtcars$vs, mtcars$gear, mtcars$am, exclude= NULL)

But that just creates a summary of counts withn each subgroups and does not create % by rows. Any suggestions are welcome. Thanks in advance.


Solution

  • The package gtsummary with its stratified gtsummary tables tbl_strata will give you what you want.

    For further details on this see here

    library(gtsummary)
      
    mtcars |> select(gear, am, vs) |> 
      mutate(vs = paste0('vs = ', vs)) |> 
      tbl_strata(
        strata = vs,
        .tbl_fun = ~.x |> tbl_summary(by = am, missing = "no") |> 
          add_n()
      ) |> 
      modify_header(label ~"am")
    

    enter image description here


    Addition

    Add percent = "row":

    mtcars |> select(gear, am, vs) |> 
      mutate(vs = paste0('vs = ', vs)) |> 
      tbl_strata(
        strata = vs,
        .tbl_fun = ~.x |> tbl_summary(by = am, percent = 'row', missing = "no") |> 
          add_n()
      ) |> 
      modify_header(label ~"am")
    

    enter image description here