How can I rename statistics in modelsummary?

50 Views Asked by At

I have a model and I like the following format from modelsummary

library(modelsummary)

fit <- lm(am ~ vs, data=mtcars)

modelsummary(
  fit,
  statistic = c('std.error', 'p.value', 'conf.int'),
  gof_map = NA,
  shape= term ~ statistic
)

However, the confidence interval limits are reffered to as 2.5% and 97.5%. Can I somehow rename them to something like "CI Lower/Upper"?

2

There are 2 best solutions below

0
Vincent On BEST ANSWER

Version 2.0.0 of modelsummary will be released in the next few days with built-in support for this. You can install it now with:

library(remotes)
install_github("vincentarelbundock/modelsummary")

Then,

library(modelsummary)

fit <- lm(am ~ vs, data=mtcars)

modelsummary(
  fit,
  statistic = c(
    'Std.Error' = 'std.error', 
    'P val' = 'p.value', 
    'Lower' = 'conf.low',
    'Upper' = 'conf.high'),
  gof_map = NA,
  shape= term ~ statistic
)

+-------------+-------+-----------+-------+--------+-------+
|             | (1)                                        |
+-------------+-------+-----------+-------+--------+-------+
|             | Est.  | Std.Error | P val | Lower  | Upper |
+=============+=======+===========+=======+========+=======+
| (Intercept) | 0.333 | 0.118     | 0.008 | 0.093  | 0.574 |
+-------------+-------+-----------+-------+--------+-------+
| vs          | 0.167 | 0.178     | 0.357 | -0.197 | 0.531 |
+-------------+-------+-----------+-------+--------+-------+ 
0
knitz3 On

Looks like modelsummary() outputs an object of class "kableExtra" "knitr_kable". These types of functions are kind of like wrappers that do the tedious things for you, like getting information from summary(fit), etc.

The documentation for modelsummary() is pretty big... if I just wanted a tiny change like this I might just edit the object directly, since it kable output is really just html. Kind of a hacky solution. Alternatively you might look into knitr::kable() or the kableExtra package to create your own tables.

library(modelsummary)

fit <- lm(am ~ vs, data = mtcars)

out <- modelsummary(
  fit,
  statistic = c("std.error", "p.value", "conf.int"),
  gof_map = NA,
  shape = term ~ statistic
)
typeof(out)
#> [1] "character"
cl   <- class(out)
atts <- attributes(out)

out <- out |>
  as.character() |>
  sub("2\\.5 %", "CI Lower", x = _) |>
  sub("97\\.5 %", "CI Upper", x = _)
class(out) <- cl
attributes(out) <- atts
out

Created on 2024-03-28 with reprex v2.1.0