rr-markdowntexreg

Why does `texreg` argument `scalebox` now throw an error when trying to render Rmarkdown pdf document?


I recently updated my OS, packages, RStudio and R and I tried to run a .Rmd file that worked fine before all the updates. When I ran the .Rmd, I was getting the an error at the end (after it reachd 100%) when trying to render a PDF document (seen below). After breaking up and running my Rmarkdown file piece by piece, I discovered the problem was the scalebox = argument I used to produce a table with texreg. I'm glad I discovered the issue but I am curious why scalebox does not work in an Rmarkdown document anymore. Reprex below (if you remove scalebox = .75, it will render just fine). Any thoughts?

title: "Reprex"
author: "Author"
date: ""
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(texreg)

df <- data.frame(y = rnorm(100),
                 x = rnorm(100))

model <- lm(y ~ x, data = df)


```{r, results='asis'}
texreg(model,
       scalebox = .75)
output file: Reprex.knit.md

! LaTeX Error: Can be used only in preamble.

Error: LaTeX failed to compile Reprex.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See Reprex.log for more info.
Execution halted

Solution

  • To use scalebox = 0.75, texreg needs to use the graphicx package. It isn't set up to work with knitr, so it just outputs the \usepackage{graphicx} command ahead of the table, where it's illegal. I imagine you're supposed to cut and paste the output into your document, with that line going into the preamble instead of the body.

    To work around this design, just set use.packages = FALSE in the call to texreg(). Since knitr already uses graphicx, that's sufficient.

    If you get the same error with some package that knitr doesn't include (maybe you used siunitx = TRUE, which needs the siunitx package), then you'll need to display the result to figure out which package it needs, and then add that to the YAML of the document, e.g.

    texreg(model,
           scalebox = .75, siunitx = TRUE)
    
    \usepackage{graphicx}
    \usepackage{siunitx}
    ...
    

    which tells you to add this to your YAML, before running with use.packages = FALSE:

    output: 
      pdf_document:
        extra_dependencies: siunitx
    

    and then the code chunk would be changed to

    texreg(model,
           scalebox = .75, siunitx = TRUE, use.packages = FALSE)