Suppose I have many models I would like to summarize in separate tables. One way to do this would be to write out each model in a modelsummary call as follows
library(modelsummary)
fit_1 <- lm(vs ~ am, data=mtcars)
fit_2 <- lm(mpg ~ am, data=mtcars)
modelsummary(
models = list('First Model' = fit_1),
statistic = c(
'Std.Error' = 'std.error',
'P val' = 'p.value',
'Lower' = 'conf.low',
'Upper' = 'conf.high'),
gof_map = NA,
shape= term ~ statistic
)
modelsummary(
models = list('Second Model' = fit_2),
statistic = c(
'Std.Error' = 'std.error',
'P val' = 'p.value',
'Lower' = 'conf.low',
'Upper' = 'conf.high'),
gof_map = NA,
shape= term ~ statistic
)
When I render my pdf using quarto, this produces two model summaries as expected. However, one can imagine that this gets repetitive for more than a few models, especially if I would like to change the tables slightly. Hence, I can write a function to make these tables
models<- list(
'First Model'=fit_1,
'Secpond Model' = fit_2
)
do_modelsummary <- function(model, model_name){
mod <- list(model)
names(mod) <- model_name
modelsummary(
models = mod,
statistic = c(
'Std.Error' = 'std.error',
'P val' = 'p.value',
'Lower' = 'conf.low',
'Upper' = 'conf.high'),
gof_map = NA,
shape= term ~ statistic
)
}
I can then loop through the list as follows
for(i in length(models)) {
fit <- models[[i]]
nm <- names(models)[[i]]
do_modelsummary(fit, nm)
}
This does not display the table upon rendering the pdf. Additionally, purrr::imap -- which does this more succinctly -- errors when attempting to render the pdf.
purrr::imap(models, do_modelsummary)
ERROR:
compilation failed- error
File ended while scanning use of \@xverbatim.
<inserted text>
\par
<*> Untitled.tex
see Untitled.log for more information.
If I want to display multiple model summaries individually and render to pdf, what is the preferred way which is not doing each table indivudually.
Seems like the key here was setting
results='asis'in the code chunk in which performs the loop. Then, the loop and the call toimaprender the tables.