How to Format Observation Numbers with Commas in 'modelsummary' Output in R

43 Views Asked by At

I'm using the modelsummary package in R to generate a summary of my model, and I'd like to format the number of observations (nobs) with commas as thousand separators. I've tried several approaches, but none have worked so far. Here's what I've attempted:

format_nobs <- function(x) {
    if (is.numeric(x)) {
        return(format(x, big.mark = ",", scientific = FALSE))
    }
    return(x)
}

And in the gof_map:

gm <- tibble::tribble(
    ~raw,            ~clean,       ~fmt,
    "nobs",          "N",          format_nobs,
    "adj.r.squared", "Adj. R²",    2
)

This resulted in an error: Error in x$raw : $ operator is invalid for atomic vectors.

Using a sprintf format string:

gm <- tibble::tribble(
    ~raw,            ~clean,       ~fmt,
    "nobs",          "N",          "%'.0f",
    "adj.r.squared", "Adj. R²",    "%.2f"
)

This resulted in the error: Error in sprintf(fmt, k) : invalid format '%'.0f'; use format %d, %i, %o, %x oder %X for integer objects.

I would like to know how to properly format the number of observations in the modelsummary output to include commas as thousand separators. Any suggestions or alternative methods to achieve this would be greatly appreciated.

1

There are 1 best solutions below

0
Vincent On

You can use the list syntax illustrated on the modelsummary website: https://modelsummary.com/vignettes/modelsummary.html#gof_map

library(modelsummary)
dat <- rep(list(mtcars), 1000)
dat <- do.call("rbind", dat)
mod <- lm(mpg ~ wt + cyl, dat)

format_nobs <- function(x) {
    if (is.numeric(x)) {
        return(format(x, big.mark = ",", scientific = FALSE))
    }
    return(x)
}

gm <- list(
  list("raw" = "nobs", "clean" = "N", "fmt" = format_nobs),
  list("raw" = "adj.r.squared", "clean" = "Adj. R2", "fmt" = 2))

modelsummary(mod, output = "markdown", gof_map = gm)
(1)
(Intercept) 39.686
(0.052)
wt -3.191
(0.023)
cyl -1.508
(0.012)
N 32,000
Adj. R2 0.83