Search code examples
r

Modify format in table1


One of the vignette examples of table1, shows a reformatting of the continuous summary stats:

my.render.cont <- function(x) {
    with(stats.apply.rounding(stats.default(x), digits = 2),
         c("", "Mean (SD)" = sprintf("%s (&plusmn; %s)",  MEAN, SD)))
}

How do I also apply a comma thousand separator in addition to the above?


Solution

  • Using ?table1::stats.apply.rounding we can discover that the default rounding function is:

    rounding.fn The function to use to do the rounding. Defaults to signif_pad.

    as well as:

    ... Further arguments.

    While not clearly stated often the purpose of ellipses is to pass additional arguments to other functions.

    If we then check ?table1::signif_pad:

    ... Further options, passed to formatC (which is used internally). Not all options will work, but some might be useful (e.g. big.mark, decimal.mark).

    And a short test later, we find that it is possible to pass big.mark = "," to table1::stats.apply.rounding() through to formatC() like so:

    library(table1)
    
    set.seed(42)
    
    data <- data.frame(x = sample(1000:9999, 10))
    
    my.render.cont <- function(x) {
      with(
        x |>
          stats.default() |>
          stats.apply.rounding(digits = 2, big.mark = ","),
        c(
          "",
          "Mean (SD)" = sprintf("%s (&plusmn; %s)", MEAN, SD)
        )
      )
    }
    
    table1(~ x, data = data, render.continuous = my.render.cont)
    

    Created on 2024-08-30 with reprex v2.1.1