Max R. P. Grossmann

Max R. P. Grossmann

How I use texreg

Posted: 2024-04-24 · Last updated: 2024-04-24

texreg1 is a really excellent R package to generate—among other output formats—LaTeX tables from R regression models. Here's how I use it:


tt <- function (models, no_resize = F, ...) {
    out <- gsub("\\begin{table}", "\\begin{table}[H]", fixed = T,
                gsub("table-text-alignment=right", "table-text-alignment=center", fixed = T,
                     gsub(" (\\d+) ", "{\\1}",
                          texreg(
                                 models,
                                 label = deparse(substitute(models)),
                                 stars = c(0.01, 0.05, 0.1),
                                 booktabs = T,
                                 siunitx = T,
                                 digits = 3,
                                 ...
                          )
                     )
                )
    )

    if (!no_resize) {
        gsub("\\begin{tabular}", "\\resizebox{\\textwidth}{!}{%\n\\begin{tabular}", fixed = T,
             gsub("end{tabular}", "end{tabular}}", fixed = T,
                  out
             )
        )
    }
    else {
        out
    }
}

This function wraps texreg::texreg(), and you can call it like this:

my_models <- list(lm(y ~ x), lm(y ~ x + z))
print(tt(my_models))

What does this do? Very simple:

  1. It puts the table where it belongs (at the code position).
  2. It resizes the table so that it fits exactly the width of the page. Can be disabled by using tt(…, no_resize = T).
  3. It center integers, such as the number of observations, while correctly aligning non-integers. This is useful if there are negative coefficients.
  4. It uses the models argument's true name as a LaTeX label.
  5. It uses proper table styling via booktabs.
  6. It uses proper (economic) thresholds for p-values and the number of digits.

This will require you to use the LaTeX packages booktabs, siunitx and graphicx.

Don't forget to submit praise to texreg's author by using texreg::praise(), and, if possible, citing1 the package. Thanks, author!


1 Leifeld, Philip (2013): texreg: Conversion of Statistical Model Output in R to LaTeX and HTML Tables. Journal of Statistical Software 55(8): 1-24. doi:10.18637/jss.v055.i08