rgtsummary

Change statistics argument so, that dichotomous variables show number of both manifestations separated by slash ( / )


I need to prepare a clinical characteristics table showing not just the frequency of one manifestation of a dichotomous variable, but both on the same line seperated by a / (slash).

For example:

Sex (female, male): 10/8

However, I'm not able to do that. The only thing I can do is number in relation to total number of observations:

data("mtcars")
require(gt_summary)

tbl_summary(mtcars,
            statistic = list(
            all_continuous() ~ "{mean}±{sd}",
            all_dichotomous() ~ "{n}/{N}"
        )
            )

I also tried:

tbl_summary(mtcars,
            statistic = list(
            all_continuous() ~ "{mean}±{sd}",
            all_dichotomous() ~ "{n}/{N-n}"
        )
            )

but that won't work.

The journal unfortunately forces this style.

Any ideas?


Solution

  • This required some workaround to achieve using the "stargazer" package. See code below.

    install.packages(c("tidyverse","foreach","stargazer"))
    library(tidyverse)
    
    data(mtcars)
    mtcars[c(2,8:11)] <- lapply(mtcars[c(2,8:11)], function(x) factor(x, ordered = FALSE)
    
    a <- mtcars %>% 
    select_if(~is.numeric(.)) %>% 
    summarise(across(everything(), list(N = ~str_c(round(mean(.),2), " ± ", round(sd(.),2))))) %>% 
    as.data.frame() %>% 
    pivot_longer(
      cols = everything(),
      names_to = c("Characteristic", ".value"),
      names_sep = "_"
    )
    
    categorical_var <- mtcars %>% select_if(~!is.numeric(.)) %>% colnames(.) %>% as.vector()
    
    library(foreach)
    
    b <- foreach(i = categorical_var, .combine = 'rbind') %do% {
      temp <- mtcars %>% 
    select(i) %>% 
    group_by(get(i)) %>% 
    count() %>% 
    rename(Characteristic = `get(i)`, N = n)
      temp[[1]] <- str_c(i, " ( ", paste0(temp[[1]], collapse=", "), " )")
      temp[[2]] <- str_c(temp[[2]], collapse=" / ")
      temp
    }
    
    b <- b %>% distinct(.)
    
    c <- rbind(a,b)
    
    library(stargazer)
    stargazer(c, type="html", summary=F)
    

    Running the function "stargazer" with type set to "html" will print out the HTML code for the table in the R console. You can copy-paste the code generated into a text editor (I prefer Notepad++) to save it as a HTML file type, and open it in a web browser of your choice (Edge, Chrome, Firefox, etc.). The final table will look like this:

    final table

    Note - All the individual code chunks can be packaged nicely into a custom function as well. Feel free to modify as needed.