I am working with stargazer
and I want to produce a LaTeX
output for a simple lm
object. The problem is that I cannot set align = TRUE
without getting an error.
LaTeX Error: \caption outside float.
I checked it and what the message says is wrong. Copying the Stargazer
output directly into an Latex document works fine. Copying it into an rmarkdown
document produces the same error (which is no surprise but I just wanted to be sure). After playing around a bit I figured out that it is working in rmarkdown
if the significance stars(*) are removed (or to precise the ^{***}
). However, stargazer
is producing them by default and they are also an important part of the output.
Is there a way to make it work?
---
header-includes:
- \usepackage{dcolumn}
output: pdf_document
---
## R Markdown
```{r, include = FALSE}
library(stargazer)
df <- data.frame(x = 1:10 + rnorm(100),
y = 1:10 + rnorm(100))
reg <- lm(y ~ x, data = df)
```
```{r, results='asis', echo = FALSE}
stargazer(reg, header = FALSE, align = TRUE)
```
On linux systems, wrapping stargazer inside either invisible
or suppressMessages
works to suppress the garbage that otherwise gets rendered. Unfortunately, this solution does not seem to work on windows computers.
---
header-includes:
- \usepackage{dcolumn}
output: pdf_document
---
## R Markdown
```{r, include = FALSE}
library(stargazer)
df <- data.frame(x = 1:10 + rnorm(100),
y = 1:10 + rnorm(100))
reg <- lm(y ~ x, data = df)
```
```{r, results='asis', echo = FALSE}
invisible(stargazer(reg, header = FALSE, align = TRUE))
# suppressMessages(stargazer(reg, header = FALSE, align = TRUE)) # also works
```
The reason is that (from the help page)
stargazer uses cat() to output LaTeX/HTML code or ASCII text for the table. To allow for further processing of this output, stargazer also returns the same output invisibly as a character vector.
We use suppressMessages
or invisible
to ensure that only the first output (produced by cat) is rendered. The character vector output turns to garbage when rmarkdown attempts to render it using print
, rather than cat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With