rdigitsgtsummary

How to format the number of digits for categorical variables in 'gtsummary::tbl_summary'?


I am unable to figure out how to tell the tbl_summary function to display decimal places when summarizing categorical variables. It works quite well with continuous variables like 'mpg', but not for 'cyl'.

library(tidyverse)
library(gtsummary)

# with decimal places
mtcars %>% 
  select(mpg) %>% 
  tbl_summary(digits = list(everything() ~ c(2)))

# no decimal places
mtcars %>% 
  select(cyl) %>% 
  tbl_summary(digits = list(everything() ~ c(2)))

Thanks!

Richi


Solution

  • To update the number of digits the percentages are rounded to use the digits= argument. In the example below, pass c(0, 2). The zero indicates to round the N to the nearest integer, and the 2 indicates to round the percentage to 2 decimal places.

    Happy Coding!

    library(gtsummary)
    packageVersion("gtsummary")
    #> [1] '1.4.0'
    
    # with decimal places
    tbl <-
      mtcars %>% 
      select(cyl) %>% 
      tbl_summary(digits = list(all_categorical() ~ c(0, 2)))
    

    enter image description here Created on 2021-04-15 by the reprex package (v2.0.0)