TexReg and Stargazer not working in Rmarkdown [duplicate] - r

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

Related

How to run r code within the latex code in Rmarkdown

Consider the following code in Rmarkdown, which produces a graph as below:
\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{example-image-a}
\caption{A test caption}
\end{figure}
Output:
Now, instead of just using a graph, I would like to create my own plot in Rmarkdown, for example, using this code:
\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{plot(mtcars$mpg)}
\caption{A test caption}
\end{figure}
but the following error is produced instead:
! LaTeX Error: File `plot(mtcars$mpg)' not found.
Is there any way to run r codes within latex?
R Markdown doesn't work this way. If you are using RStudio, it is pretty easy. In the R Markdown file, type
plot(mtcars$mpg)
In other words, you need to start your code with three back-ticks and {r}, and stop your code with three back-ticks again. Your R code written this way will produce the plot you require. After that, click on "knit" button, or use rmarkdown::render(your_file_name).
What you have written in the question means you have produced this chart, and saved that chart as a file in your working directory. If you have saved your plot in the working directory, your code will still work. Try it.
you could try plotting to a file device in an R code chunk e.g.
png(filename="mtcars_mpg.png")
plot(mtcars$mpg)
dev.off()
You can hide this chunk by using include = FALSE in the chunk options.
Then just bring the file in with your LaTeX code:
\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{mtcars_mpg.png}
\caption{A test caption}
\end{figure}

How to specify plot size together with plot code in Sweave or Knitr

I am trying to produce a document using Sweave or Knitr which contains plots.
Here is a minimal example for Sweave:
\documentclass{article}
\title{Plot example}
\begin{document}
\maketitle
<<setup>>=
library("graphics")
myplot = function(n) {
plot(cumsum(rnorm(n)),type="l",main="The stock market",ylab="Money",xlab="Time")
}
#
This is what the stock market looks like over the past month:
\begin{center}
<<fig=T,echo=F,width=10,height=4>>=
myplot(10)
#
\end{center}
and over the past decade:
\begin{center}
<<fig=T,echo=F,width=10,height=4>>=
myplot(1000)
#
\end{center}
\end{document}
The Knitr version has slightly different chunk headers:
<<echo=F,fig.width=10,fig.height=4>>=
The output looks like this:
In both cases, the width and height of the plots are hard-coded in the source file. This seems to me like bad software design. I would prefer to specify the width and height of the plots within the function myplot(). Otherwise, if I want to change the way the plots look, or if I want to switch from letter paper to A4 paper, then I have the cumbersome task of changing several hard-coded width and height values using search and replace.
In Knitr, it is possible to change the default width and height through R code:
<<cache=FALSE>>=
opts_chunk$set(fig.width=3,fig.height=4);
#
However, this configuration must be separate from the code chunk in which the plot is executed, because Knitr (like Sweave) opens the plotting device before evaluating any of the chunk code. What I need is a way to specify the height and width within myplot().
What is an elegant way to specify the plot width and height together with the rest of the plot in Sweave or Knitr?
Here is a new example I came up with, which attempts to be more illustrative of a practical need for programmatic control over plot size. In this example, which uses knitr, myplot writes a plot to a PDF file, and then uses asis_output to emit an \includegraphics statement that references the same PDF file. This statement includes a width parameter that is calculated from the dimensions of the PDF, so that the two diagrams render with elements of the same size.
\documentclass{article}
\title{knitr example with variable plot width using asis\_output}
\begin{document}
\maketitle
\begin{center}
<<echo=F>>=
library("graphics")
myplot=function(n, trim=0.4) {
fn=sprintf("myplot-%d.pdf",n)
nds=letters[1:n]
ijs=expand.grid(i=1:n,j=1:n)
edges=matrix(nrow = length(nds), ncol= length(nds),
ijs$i == ijs$j+1)
arrowlabels=ifelse(edges,"","_"); # "_" == absent, below
width=n+1
height=2
pdfwidth=width-2*trim
pdfheight=height-2*trim
# plotmat expects coordinates in [0,1]
repos=function(pos) {
cbind((pos[,1]-trim)/pdfwidth,(pos[,2]-trim)/pdfheight)
}
pos=repos(cbind(1:n,1));
pdf(fn, height=pdfheight, width=pdfwidth);
par(mai=0*(1:4))
plotmat(arrowlabels, pos=pos, name=nds,
box.size=0.3/pdfwidth,
curve=0, arr.lwd=1, arr.type="simple", arr.length=0.5,
arr.pos=0.68,
box.type="circle", box.col="white",
shadow.size=0, absent="_",
txt.font=3 # italic
)
dev.off();
renderwidth=sprintf("%0.2f\\textwidth",pdfwidth/8);
asis_output(paste0("\\fbox{\\includegraphics[width=",renderwidth,"]{",fn,"}}"))
}
#
\end{center}
\begin{center}
\noindent A linked list could have as many as four elements: \\
\Sexpr{myplot(4)} \\
or even seven: \\
\Sexpr{myplot(7)}
\end{center}
\end{document}
And the output:
I made the following changes to get it to work with Sweave. The Sweave version is slightly less concise because I couldn't figure out how to invoke \Sexpr in results=tex mode.
dev.off();
renderwidth=sprintf("%0.2f\\textwidth",pdfwidth/8);
- asis_output(paste0("\\fbox{\\includegraphics[width=",renderwidth,"]{",fn,"}}"))
+ cat(paste0("\\fbox{\\includegraphics[width=",renderwidth,"]{",fn,"}}"))
}
#
\end{center}
\begin{center}
\noindent A linked list could have as many as four elements: \\
-\Sexpr{myplot(4)} \\
+<<results=tex,echo=F>>=
+ myplot(4)
+#
+\\
or even seven: \\
-\Sexpr{myplot(7)}
+<<results=tex,echo=F>>=
+ myplot(7)
+#
+\\
\end{center}
\end{document}

Render LaTeX tables in HTML using r-markdown

I am trying to render the following table in a RMD file:
\begin{table}[]
\centering
\caption{My caption}
\label{my-label}
\begin{tabular}{|l|}
\hline
\\ \hline
\end{tabular}
\end{table}
So far no success. Is there any fundamental reason why rmarkdown cannot compile LaTeX enviroments (other than equations) to HTML?
In a markdown document, the expected input markup language is (r)markdown. You should not expect pandoc to automatically recognize arbitrarily mixed markup languages. LaTeX math markup can only be used in markdown documents because there is a rmarkdown extension to handle this.
However, it is still possible to use a LaTeX table like the one shown in the question in a rmarkdown document. I demonstrated the "inverse" (markdown table in RNW document) in this answer. Please note that this a rather experimental approach that might fail in other situations.
The idea behind the function tex2markdown is explained here.
---
output: html_document
---
# My document
This is `rmarkdown`.
This table is converted from LaTeX:
```{r, results = "asis", echo = FALSE, message = FALSE}
library(knitr)
tex2markdown <- function(texstring) {
writeLines(text = texstring,
con = myfile <- tempfile(fileext = ".tex"))
texfile <- pandoc(input = myfile, format = "html")
cat(readLines(texfile), sep = "\n")
unlink(c(myfile, texfile))
}
textable <- "
\\begin{table}[]
\\centering
\\caption{Food order}
\\begin{tabular}{| l | l |}
\\hline
Hamburgers & 3 \\\\
Hot dogs & 2 \\\\ \\hline
\\end{tabular}
\\end{table}
"
tex2markdown(textable)
```
---
Time for *lunch*.
Not all LaTeX features can be converted to HTML, but for simple tasks this should work. Note that backslashes need to be escaped by an additional backslash.
This is mainly a proof of concept. For production, use LaTeX tables in RNW documents and markdown tables in RMD documents!

Problems cross referencing in LaTex with knitr and xtable

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.

Using stargazer with Rstudio and Knitr

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

Resources