27

I'm struggling to use stargazer output in knitr, using RStudio. For example, I paste the code below into a .Rmd file, then click Knit HTML. The first block between [ and ] is rendered as equations. The second block is from stargazer. It remains as code. When I paste the second block, less [ and ], into a Sweave file and then click compile as PDF, the code renders as a table. I have MikTex installed and version 3 of Stargazer.

The answer inserting stargazer or xable table into knitr document works for me in a Sweave file (Rnw) when clicking compile PDF. In an Rmd file, the tex is not rendered when clicking Knit HTML.

How can I put stargazer output into a Rmd file so that Knit HTML converts the latex code to a table? (I'm new to Latex, and am not sure what code I can delete, so apologise for the long segment.)

\[
\begin{aligned}
\dot{x} & = \sigma(y-x) \\
\dot{y} & = \rho x - y - xz \\
\dot{z} & = -\beta z + xy
\end{aligned}
\]

\[
\documentclass{article}

\begin{document}


% Table created by StarGazer v.3.0.1 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu
% Date and time: Sun, Feb 03, 2013 - 11:34:52 AM
\begin{table}[htb] \centering 
  \caption{} 
  \label{} 
\footnotesize 

\begin{tabular}{@{\extracolsep{5pt}}lc} 
\\[-1.8ex]\hline 
\hline \\[-1.8ex] 
 & \multicolumn{1}{c}{\textit{Dependent variable:}} \\ 
\cline{2-2} 
\\[-1.8ex] & Rate \\ 
\hline \\[-1.8ex] 
 pole & $0.071^{***}$ \\ 
  & $(0.020)$ \\ 
  & \\ 
 post & $0.095^{***}$ \\ 
  & $(0.019)$ \\ 
  & \\ 
 Constant & $-5.784^{***}$ \\ 
  & $(1.667)$ \\ 
  & \\ 
\hline \\[-1.8ex] 
Observations & $46$ \\ 
Residual Std. Error & $2.378 (df = 43)$ \\ 
\hline 
\hline \\[-1.8ex] 
\textit{Note:}  & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\ 
\normalsize 
\end{tabular} 
\end{table} 

\end{document}
\]
5
  • 2
    LaTeX tables do not work in Markdown/HTML. Only math is supported by RStudio. Tables have their own syntax (click the MD button), and the question is whether stargazer supports the syntax. I only know xtable can generate HTML tables.
    – Yihui Xie
    Feb 3, 2013 at 17:43
  • @Yihui googleVis package has html table capabilities. developers.google.com/chart/interactive/docs/gallery/table Feb 5, 2013 at 16:30
  • Could you please be more specific about what you are trying to achieve. Most importantly, do you need an HTML file as your final output, or do you need PDF or Word with HTML being an intermediate step?
    – Maxim.K
    Apr 12, 2013 at 15:11
  • If you don't have to use stargazer, texreg is compatible with knitr and HTML/Markdown. See section 5.6 of cran.r-project.org/web/packages/texreg/vignettes/jss1020.pdf. Oct 17, 2013 at 7:20
  • @Isaiah I think you should change the accepted answer to the second answer Jun 12, 2018 at 9:18

5 Answers 5

52

Use the following code and you get a working version

```{r, results='asis'}
stargazer(model)
```

When converting to pdf, the following code works perfectly for stargazer 4.0:

```{r, results='asis'}
stargazer(model, header=FALSE, type='latex')
```
3
  • This works well, but the auto-generated LaTeX comments from stargazer don't get hidden in my PDF output: % Table created by stargazer v.5... How do you prevent this? Feb 5, 2016 at 23:29
  • 5
    header=FALSE takes care it for me. Not sure if you missed this option.
    – Junchen
    Jun 24, 2016 at 3:56
  • Wondering if @Junchen or others have been able to make stargazer work within a fuction. Something like this: fits <- lapply(unique(temp$measure2), function(z) stargazer( lm(value~groupID, data=dt2[J(z), ], y=TRUE), header=FALSE,type="html" ) ) fits
    – Ben
    Oct 17, 2018 at 19:54
13

Since the topic has gone a bit stale, I'll assume the issue at hand is to somehow use stargazer with knitr, and not per se the conversion of the stargazer objects into HTML.

Being an avid fan of stargazer, I have come up with the following workflow:

  1. Write my code in an .Rmd file.
  2. Knit it into .md. Stargazer tables remain as LaTeX code in the resulting markdown file.
  3. Use pandoc to convert the markdown file to PDF. Pandoc translates the LaTeX code into proper tables. Alternatively, one can use LyX with knitr plugin to get stargazer tables nicely output in PDF format.

If one wants stargazer tables in MS Word, the best way I have found is to use LaTeX2RTF. Although the very top cells are distorted a bit, fixing it is a matter of removing an erroneous empty cell. For the rest the table is preserved and can be pasted/imported into Word.

These two strategies help use stargazer outside LaTeX. Hope it helps.

2
  • 1
    Did you manage to render equations correctly by any chance? That's the only thing I can't get to work with this workaround
    – altabq
    Feb 11, 2018 at 19:45
  • I can't get datetime right too, shows like posix integer
    – eri0o
    Aug 29, 2021 at 13:10
6

In addition to the previous answer, and maybe as a simpler solution, it is possible for stargazer to output the table in html code so that when the Rmd file is knitted into html, a table is created rather than the tex code. I believe that the stargazer function can now export directly to html by setting type = 'html'.

So for example, given model fit lm1, you would use the following code in your Rmd file:

stargazer(lm1, type = 'html')

This works whether you want your final output to be html or pdf.

5

Returning to this question.

I want to use the same markdown files to produce html and pdf outputs in RStudio with knitr. That is, in RStudio I want to push the knit button, and have the options of either knitting a HTMl output, or a pdf output. I have no great interest, at the moment, in knitting a word/OpenOffice document.

I used the amazingly useful stargazer cheatsheet from Jake Russ. This exercises most of stargazer's functions. It is an R MArkdown file, with the chunk option results='asis' set for those chunks producing stargazer output.

The stargazer command itself has an argument 'type'. The default is type='latex' In Jake Russ's cheatsheet, which is intended to produce a webpage, type='html' is used throughout.

This does not work at all if you try to knit it into a pdf. Tables come out as long lists, one table cell per line, with no formatting, and occupying many pages, with no formatting.

The smallest change that I can make to allow me to produce nice pdf's within RStudio is to globally replace all the

type='html'

with

type='latex'

(note that both occur in the text of the document, as well as in the stargazer commands, so care is needed!)

This works! As far as I can see the pdf is a faithful replica of the webpage, which is exactly what I want.

Trying to knit OpenOffice documents, if I leave

type='latex'

Each table in the output is replaced by this text:-

% Table created by stargazer v.5.2 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu % Date and time: Tue, Sep 01, 2015 - 22:22:29

If I restore the

type='html'

then each table is written, one cell per line, down the side of the page with no formatting!

1
  • "globally replace"... I'd like to replace the type with one line, instead of every individual table.
    – ahorn
    Jul 23, 2021 at 10:03
2

Stargazer is amazing but hasn't been updated in a while and so isn't designed to interact specifically with knitr or RStudio's interactive viewer options. The lack of interactive viewing and automatic html/latex detection leads to at least two issues:

  • This can be especially confusing for new users of R who expect easy-to-read inline output in RStudio

  • It can also be frustrating in more complicated documents when knitting a large html or latex table takes time

Below I've created a simple wrapper around the stargazer function called starviewer that does the following:

  • check if the document is being knit to latex or html
  • if the document isn't being knit to latex, output to text or html
  • when run interactively in RStudio, output can appear inline as text and/or in the Viewer pane as html

For more on RStudio's viewer function, rstudioapi::viewer(), see: https://rstudio.github.io/rstudio-extensions/pkgdown/rstudioapi/reference/viewer.html

The following four code chunks should work within a standard R markdown document and automatically assign the correct type (latex or html) when knitting. They should also run interactively and output inline and/or to the Viewer pane.

Finally, for automatic conversion of a stargazer table to formats that include Word (using an image of the html output) see this solution: https://stackoverflow.com/a/63563742/893399

```{r load_packages}
# good to load stargazer for regular usage
library(stargazer)
```

```{r starviewer_function}

# create wrapper around stargazer
starviewer <- function(...) {
  
  # make sure stargazer is available
  require(stargazer)
  
  # assume text output but check for latex or html
  star_format <- "text"
  if(knitr::is_latex_output()) {star_format <- "latex"}
  if(knitr::is_html_output())  {star_format <- "html"}
  
  # if latex, just run stargazer as usual
  if (star_format == "latex") {
    stargazer::stargazer(...)   

  } else {

  # if not latex, run stargazer in text / html (or both)  
    dir <- tempfile()
    dir.create(dir)
    htmlFile <- file.path(dir, "tempfile.html")
    stargazer::stargazer(..., type = star_format, out = htmlFile)
    rstudioapi::viewer(htmlFile)
  }
}

```

```{r run_models}
lm1 <- lm(mpg ~ wt,      data = mtcars )
lm2 <- lm(mpg ~ wt + am, data = mtcars )
```

```{r create_table, results = 'asis'}
starviewer(lm1, lm2)

```

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.