Search code examples
rmodelsummary

How to control rounding in datasummary_df in modelsummary in R?


I like to have some variables with and some without digits (different rounding).

library(modelsummary)
datasummary_df(mtcars)

enter image description here

I like to have mpg with the two digits, whereas cyl should just be 4, 6, etc. How can I do this without converting cyl to a factor variable? Can I control the rounding of different columns in dbl format?


Solution

  • For this particular case, it's enough to ask for significant digits:

    mtcars %>%  datasummary_df(fmt = fmt_significant(digits = 3))
    

    But I suspect you want to manually specify how each column gets rounded. Depending on case, I think piping the dataset into mutate and then using round could do the trick. Say I want mpg and drat at 2 digits, but everything else down to integers.

    cols_2 <- c("drat", "mpg")
    
    mtcars %>% 
      mutate(across(c(everything(), -any_of(cols_2)),round, 0 )) %>% 
      datasummary_df(fmt = fmt_significant(digits = 3))