Search code examples
rdataframestatisticsgtsummary

Treatment effect table in R with horizontally-oriented variables


So i subsetted a dataframe to keep only my 4 columns of interest. I want to count the number of control (0) and treated (1) observations. I computed something with the gtsummary package, but the variables are vertically oriented (like here http://www.danieldsjoberg.com/gtsummary/articles/tbl_summary.html), one below each other, and this is not what i want. I searched on google but all the tables i saw have this orientation too.

I put here a picture of what i'd like to obtain, if some of you have any idea !

Desired output

code i use to obtain my initial table (same as in the link)

install.packages("gtsummary")
library(gtsummary)

trial <- finaldf %>% select(treatment, 2digID,4digID,classificationsdescription)
trial %>% tbl_summary()

t2 <- trial %>% tbl_summary(by = treatment)

I cannot put the real data but i created an example that looks like my data :

_2ID <- c(38,38,38,38,38,38,38,38,38,38,80,80,80,80,80,80,80,80,80,80)
_4ID <- c(3837,3837,3837,3812,3812,3896,3894,3894,3877,3877, 8099,8099,8027,8027,8027,8033,8033,8064,8064,8022)
descriptions <- c('ILL1','ILL1','ILL1', 'ILL2','ILL2','ILL3','ILL4','ILL4','ILL5','ILL5','ILL1','ILL1','ILL2','ILL2','ILL2','ILL3','ILL3','ILL4','ILL4','ILL5')
trt <-c(0,0,0,1,1,1,0,0,1,1,0,0,1,1,1,0,0,1,1,0)

df.data <- data.frame(_2ID,_4ID,descriptions, trt)

UPDATE - SOLVED

I think i managed to solve this problem even if my output is a dataframe and not a "publication-ready" table :

install.packages("reshape2")
library(reshape2)

data_wide <- dcast(df,_2digID+_4digID+descriptions ~ treatment, value.var="counts")

But i'm not sure yet that this gives the right numbers tho.


Solution

  • The example below gets you close, but not exactly what you're after. I like the idea of being able to support tables like this, and I'll add it to the list of features to implement!

    library(gtsummary)
    #> #Uighur
    packageVersion("gtsummary")
    #> [1] '1.4.1'
    
    tbl <-
      trial %>%
      mutate(
        grade = paste("Grade", as.character(grade)),
        stage = paste("Stage", as.character(stage))
      ) %>%
      tbl_strata(
        strata = c(stage, grade),
        ~ .x %>%
          tbl_summary(by = trt, 
                      include = response,
                      type = response ~ "categorical",
                      missing = "no",
                      statistic = response ~ "{n}") %>%
          modify_header(all_stat_cols() ~ "**{level}**"),
        .combine_with = "tbl_stack"
      ) %>%
      as_flex_table()
    

    enter image description here

    • Table truncated because it was very long!

    Created on 2021-07-14 by the reprex package (v2.0.0)