Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rmarkdown of Stargazer: LaTeX Error if align is set to TRUE

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)
```
like image 401
Alex Avatar asked Aug 08 '16 19:08

Alex


1 Answers

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
```

enter image description here

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

like image 137
dww Avatar answered Oct 18 '22 11:10

dww