I am currently working with R Studio to produce PDF documents with R/knitr in LaTex. Within these documents I want to present part of my results in tables that I want to refer to in the text. I produce these tables using the xtable package within R and it is working perfectly and giving me the right tables.
So far so good but when it come to referencing I ran into some troubles. At the moment the resulting PDF output refers to the section in which the table lies. I searched around in some LaTex help files and it is stated that this happens when the label of the floating object is placed before the caption. However when I checked the output of xtable it was placed after the caption.
Does anyone have a solution for this?
Here is an example code similar to the one I used that gives me the same kind of result in the PDF (I left all packages used in LaTex and R in to make sure it is not something caused by some interference with these).
\documentclass[preprint,authoryear]{elsarticle}
\usepackage[a4paper]{geometry}
\usepackage{natbib}
\usepackage{mathpazo}
\usepackage{booktabs}
\usepackage{dcolumn}
\usepackage[breaklinks]{hyperref}
\usepackage{hyperref,url}
\usepackage{lscape}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{amssymb}
\usepackage{gensymb}
\usepackage[allow-number-unit-breaks=true]{siunitx}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[version=3]{mhchem}
\usepackage[section]{placeins}
\usepackage[colorinlistoftodos]{todonotes}
\usepackage{float}
\usepackage{lineno}
\begin{document}
\section{Test}
This is a test. You can see the result in Tab. \ref{tab:Test}.
\section{Table}
<<Ini,eval=TRUE,include=FALSE,echo=FALSE,warning=FALSE,error=FALSE,cache=FALSE>>=
#set chunk options
opts_chunk$set(echo=FALSE,warning=FALSE,message=FALSE,dev.args=list(pointsize=12),fig.pos="!h",dpi=500)
require(stringr)
require(reshape2)
require(lubridate)
library(plyr)
library(lattice) #Needed for multi-panel graphs
library(mgcv) #Needed for smoothing curves in scatterplots
library(ggplot2)
library(ggmap)
require(gridExtra)
library(scales)
library(xtable)
require(nlme)
library(zoo)
#
<<results='asis',echo=FALSE>>=
Test<-data.frame(Test=c(1:3),a=c(4:6))
print(xtable(Test,caption="Test table",label="tab:Test",
digits=2),
include.rownames=FALSE,
caption.placement="top",
latex.environments = "left")
#
\end{document}
The result from the xtable code looks like this:
% latex table generated in R 3.0.3 by xtable 1.7-4 package
% Tue Jun 02 09:27:38 2015
\begin{table}[ht]
\begin{left}
\caption{Test table}
\label{tab:Test}
\begin{tabular}{rr}
\hline
Test & a \\
\hline
1 & 4 \\
2 & 5 \\
3 & 6 \\
\hline
\end{tabular}
\end{left}
\end{table}
When I try to run this I get 4 warning messages that seem kind of strange but there is still a PDF output. All 4 warnings are around the code that is produced by xtable. Here the output from the Log within R Studio:
! Missing $ inserted.
<inserted text>
$
l.81 \begin{left}
I've inserted a begin-math/end-math symbol since I think
you left one out. Proceed, with fingers crossed.
! Missing delimiter (. inserted).
<to be read again>
\global
l.82 \caption
{Test table}
I was expecting to see something like `(' or `\{' or
`\}' here. If you typed, e.g., `{' instead of `\{', you
should probably delete the `{' by typing `1' now, so that
braces don't get unbalanced. Otherwise just proceed.
Acceptable delimiters are characters whose \delcode is
nonnegative, or you can use `\delimiter <delimiter code>'.
! Missing $ inserted.
<inserted text>
$
l.82 \caption{Test table}
I've inserted a begin-math/end-math symbol since I think
you left one out. Proceed, with fingers crossed.
! Missing \right. inserted.
<inserted text>
\right .
l.82 \caption{Test table}
I've inserted something that you may have forgotten.
(See the <inserted text> above.)
With luck, this will get me unwedged. But if you
really didn't forget anything, try typing `2' now; then
my insertion and my current dilemma will both disappear.
I hope there is someone that is able to help me!
PS: Please note that I am not able to post a screen shot of my PDF output because I don't have enough reputation.
The left environment seems to be messing up the referencing. I tried
% latex table generated in R 3.2.0 by xtable 1.7-4 package
% Tue Jun 02 09:53:12 2015
\begin{table}[ht]
\caption{Test table}
\label{tab:Test}
\begin{left}
\begin{tabular}{rr}
\hline
Test & a \\
\hline
1 & 4 \\
2 & 5 \\
3 & 6 \\
\hline
\end{tabular}
\end{left}
\end{table}
and it produces a correct reference.
Related
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}
\]
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')
```
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:
Write my code in an .Rmd file.
Knit it into .md. Stargazer tables remain as LaTeX code in the resulting markdown file.
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.
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.
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!
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)
```
I have a small header I want to print at the top of a report. It should look like this in the end:
The report is generated by an RMarkdown/Knitr report. I am mixing in Latex to get the formatting I need. The data is based on a table I generate by pulling results from a REST Query. The dataframe in R looks like:
I coded up the LaTex code to get the result I wanted and that appears as such:
\begin{spacing}{.7}
\begin{center}
ECC \begin{tabular}{|C|C|} \hline \cellcolor{red} \textbf{\scriptsize \textcolor{white}{TOUCH}} & \textbf{\scriptsize NO TOUCH} \\ \hline \end{tabular} \hspace{.9em}
DOC \begin{tabular}{|C|C|} \hline \textbf{\scriptsize TOUCH} & \textbf{\scriptsize NO TOUCH} \\ \hline \end{tabular} \hspace{.9em}
CCC \begin{tabular}{|C|C|} \hline \textbf{\scriptsize TOUCH} & \textbf{\scriptsize NO TOUCH} \\ \hline \end{tabular} \hspace{.9em}
GEN \begin{tabular}{|C|C|} \hline \textbf{\scriptsize TOUCH} & \textbf{\scriptsize NO TOUCH} \\ \hline \end{tabular} \hspace{.9em}
IT \begin{tabular}{|C|C|} \hline \textbf{\scriptsize TOUCH} & \textbf{\scriptsize NO TOUCH} \\ \hline \end{tabular} \hspace{.9em}
\end{center}
\end{spacing}
So far, so good. But the coloring of the text and the cell colors need to be dynamic. The criteria are as follows:
If the environment is a "Touch" environment, that cell should be colored green and the text white.
If the environment is a "No Touch" environment, that cell should be colored red and the text white.
Cells not colored in each section should have a white background and black text.
Not so hard, I created a code chunk in the report that is wrapped inside of the \being{center} and \begin{spacing}{.7} items, that looks like this:
```{r echo = FALSE, warning = FALSE, message=FALSE, results='asis'}
# Add row to data frame to build table options
touchNoTouchDF$tableOption <- NA
for(i in 1:nrow(touchNoTouchDF)) {
if(strsplit(touchNoTouchDF[i,1], ":")[[1]][2] == "Touch") {
touchNoTouchDF[i,2] <- paste(strsplit(touchNoTouchDF[i,1], ":")[[1]][1],"\\begin{tabular}{|C|C|} \\hline \\cellcolor{OliveGreen!85} \\textbf{\\scriptsize \\textcolor{white}{TOUCH}} \& \\textbf{\\scriptsize NO TOUCH} \\newline \\hline \\end{tabular} \\hspace{.9em}")
} else {
touchNoTouchDF[i,2] <- paste(strsplit(touchNoTouchDF[i,1], ":")[[1]][1],"\\begin{tabular}{|C|C|} \\hline \\textbf{\\scriptsize TOUCH} \& \\cellcolor{red} \\textbf{\\scriptsize \\textcolor{white}{NO TOUCH}} \\newline \\hline \\end{tabular} \\hspace{.9em}")
}
}
for(i in 1: nrow(touchNoTouchDF)) {
print(touchNoTouchDF[i,2])
}
```
What I did here, was make a look to generate the correct LaTex code in a different column of that data frame based on what the first column contains. After running that for loop I get the data frame you see above. So far, excellent. Now is where my problem comes in. I want to have that R code chunk print that LaTex so it is rendered. I figured I simple for loop with a print statement would work, no dice. I tried cat(), that didn't work either.
I'm perplexed as to how I can get the contents of that last row printed out so the pdf report that is generated contains that graphical representation. Any ideas? Tips? I'm sure this is simple, but I have been at this for couple hours and Google'd it various ways... Thanks in advance!
EDIT:
As requested, below is the output of what I am getting. I made sure to use cat(), which, if I run this manually, prints the LaTex out to the console with no issues. When I attempt to knit the document, I get the following:
! Misplaced \noalign.
\hline ->\noalign
{\ifnum 0=`}\fi \let \hskip \vskip \let \vrule \hrule \let...
l.143 ...tbf{\scriptsize NO TOUCH} \newline \hline
pandoc.exe: Error producing PDF
Error: pandoc document conversion failed with error 43
In addition: Warning messages:
1: package 'knitr' was built under R version 3.3.2
2: package 'prettyR' was built under R version 3.3.2
3: package 'magick' was built under R version 3.3.2
4: running command '"C:/Users/z10987/AppData/Local/Pandoc/pandoc" +RTS -K512m -RTS pdfReport.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output pdfReport.pdf --template "C:\R\R-3.3.1\library\rmarkdown\rmd\latex\default-1.17.0.2.tex" --highlight-style tango --latex-engine xelatex --include-in-header header1.tex --variable graphics=yes' had status 43
Execution halted
I thought, maybe, it was because I did not escape the "&" in the table, but when I tried that I got:
Error: \& is an unrecognized escape character in string...
Thanks again!
UPDATE:
I figured it out - in the table, originally, at the end of each line there was a \\. I attempted to escape this by \\\, which gave me an error. I decided that since I thought \\ was a newline, I'd just replace it with \\newline. I guess you have to have \\ at the end of a table, or it doesn't like it.
So... I put the \\ back in. Now, but I still had the issue with escaping it. Just on a whim, I figured, well, "if one \ escapes the other \, maybe I need two, one to escape each backslash..." I replaced the \\ with \\\\ and voila! It worked. Ugh, such simple things.... I wanted to post the solution for this.
All - to post an official answer, my mistake was thinking I could escape "\" with a single "\", thus, I was pasting into my string "\\". However, since each "\" must be escaped. I had to escape the first "\" and then the second "\", therefore ending up with "\\". The first escapes the second, and the third escapes the fourth. Probably something basic, but is an easy oversight if you aren't paying attention. Just wanted to post the answer for others.
I am using Rstudio with knitr/rmarkdown/pandoc/latex to render .Rmd code to pdf. I have been struggling with certain latex code being rendered exactly as expected while very slightly different code ends up not being parsed correctly, which results in my .tex file containing lines like "\textbackslash{}begin{table}" instead of "\begin{table}".
Googling reveals similar mis-parsing when dealing with HTML, but I'm going straight from .Rmd to .md to .tex to .pdf.
This is all dependent on the particular version/platform of Rstudio I'm using, as well as the R packages knitr, xtable, rmarkdown, an rmarkdown template, etc., so I've been struggling to come up with an MWE.
(I did check that m,y version of pandoc is >= 1.13, because Googling suggested there's a bug in earlier versions that may be related.)
However, I've now got a kinda MWE that I can at least isolate to how pandoc is parsing its temporary .utf8.md file to create the .tex file.
The following markdown is parsed correctly from .md to .tex to .pdf:
# Data Profile
\begin{table}[htbp]
\centering
\parbox{12cm}{\caption{\small Record Count of Things Summarized in this Table.\label{MyRef}\vspace{4pt}}}
{\small
\begin{tabular}{llrrr}
Thing & Characteristic & Aspect 1 & Aspect 2 & Aspect 3 \\
\hline
Some & data & rows & go & here \\
more & data & rows & go & here \\
\end{tabular}
}
\end{table}
But another bit of markdown, which is identical in every way to what's above except for lacking the \parbox around the \caption (which is how the R xtable package implements its own caption.width option), gets completely mangled. The relevant alternate line:
\caption{\small Record Count of Things Summarized in this Table.\label{MyRef}\vspace{4pt}}
These two markdown chunks are parsed according to the command below by Rstudio into the respective .tex chunks. I've satisfied myself that this is happening during pandoc processing because I can see that the .utf8.md files with and without the \parbox are otherwise identical, but the resulting .tex files differ, and everything else (the rmarkdown template, the pandoc options, etc.) stays exactly the same.
/usr/local/rstudio-0.98.1103/bin/pandoc/pandoc +RTS -K512m -RTS MyDoc.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output MyDoc.tex --filter /usr/local/rstudio-0.98.1103/bin/pandoc/pandoc-citeproc --template /home/user/R/x86_64-unknown-linux-gnu-library/3.2/MyRmarkdownTemplate/rmarkdown/templates/report/resources/template.tex --highlight-style tango --latex-engine pdflatex --bibliography bibliography.bib
Good:
\begin{table}[htbp]
\centering
\parbox{12cm}{\caption{\small Record Count of Things Summarized in This table.\label{MyRef}\vspace{4pt}}}
{\small
\begin{tabular}{llrrr}
Thing & Characteristic & Aspect 1 & Aspect 2 & Aspect 3 \\
\hline
Some & data & rows & go & here \\
more & data & rows & go & here \\
\end{tabular}
}
\end{table}
Bad:
\textbackslash{}begin\{table\}{[}htbp{]} \centering
\textbackslash{}caption\{\small Record Count of Things Summarized in This Table.\label{MyRef}\vspace{4pt}\} \{\small
\begin{tabular}{llrrr}
Thing & Characteristic & Aspect 1 & Aspect 2 & Aspect 3 \\
\hline
Some & data & rows & go & here \\
more & data & rows & go & here \\
\end{tabular}
\} \textbackslash{}end\{table\}
In other words, for some reason, without that \parbox, pandoc doesn't realize that it's parsing latex until it reaches the \small inside the opening brace just before the \begin{tabular}. With the parbox, it knows it's latex right at the first backslash in the \begin{table}.
So my question is: What's up with this? And how do I fix it?
Turns out it was that \vspace inside the caption, or at least removing that leads to correct parsing. Must be non-standard enough that the LaTeX reader fails.
See Yihui's comment on the original question. His link (https://github.com/jgm/pandoc/issues/2493) indicates that pandoc's LaTeX parser silently falls back to interpreting problematic LaTeX as plain text, which I think explains what's happening here.
I have a tex file like the following to be converted to docx by Pandoc.
\documentclass[12pt]{report}
\begin{document}
% latex table generated in R 3.0.1 by xtable 1.7-1 package
\begin{table}[!h]
\centering
\begin{tabular}{rlll}
\hline
& PIK3CA & APC & ALDH2 \\
\hline
Detection point & 120\~{}121 & 102\~{}104 & 76\~{}78 \\
Genotype & -/- & A/A & G/G \\
\hline
\end{tabular}
\end{table}
\end{document}
When I use the Pandoc program (v1.11.1) to convert it, the docx content has this extra [!h] string, which should not exist as it's only a table placement parameter.
[!h]
PIK3CA APC ALDH2
Detection point 120~121 102~104 76~78
Genotype -/- A/A G/G
And if I use [ht] as the placement parameter, I'd have an extra string of [ht] in converted docx.
Any suggestion to avoid it? Or is it just Pandoc couldn't handle it right the moment?
After more investigation, I think I found the mechanism behind it.
Per a discussion about floating figures and tables by Pandoc at Google Groups and then Pandoc release notes(search 'longtable' on the notes page), Pandoc currently use longtable for table formating and longtable actually doesn't do floating. This means no placement parameter is accepted by Pandoc, although by default the R package xtable generates the [ht] parameter.
So for anyone that uses xtable together with knitr and wants to convert the result to docx, you need hack the generated tex file by removing the placement parameter [ht]. (code adopted from Yihui)
x = readLines('foo.tex')
# remove any placement parameters generated by xtable
x = gsub('(\\\\begin\\{table\\}).+', '\\1', x)
# write the processed tex file back
writeLines(x, 'foo.tex')
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}
\]
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')
```
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:
Write my code in an .Rmd file.
Knit it into .md. Stargazer tables remain as LaTeX code in the resulting markdown file.
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.
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.
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!
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)
```