new font style for stargazer latex table when using knitr - r

I want to print a latex table generated with stargazer() in monospaced font, and I want to do it in a reproducible way with knitr (i.e., no manual latex coding). I tried to define an environment called mymono and then wrap the knitr chunk in this environment via \begin{} and \end{}. It does not work; the table prints in the default font style.
\documentclass{article}
\newenvironment{mymono}{\ttfamily}{\par}
\begin{document}
<<lm, echo=FALSE>>=
df <- data.frame(x=1:10, y=rnorm(10))
library(stargazer)
lm1 <- lm(y ~ x ,data=df)
#
% reproducible
\begin{mymono}
<<table_texstyle, echo=FALSE, results='asis', message=FALSE>>=
stargazer(lm1, label="test")
#
\end{mymono}
\end{document}
I don't think there is a font setting in stargazer() except for font.size.
# > sessionInfo()
# R version 3.0.2 (2013-09-25)
# Platform: x86_64-apple-darwin10.8.0 (64-bit)
# other attached packages:
# [1] stargazer_5.1
Even better than wrapping the entire table{} in the new font style would be to wrap just tabular{} so that the caption remains the default style. I don't know if there is a way to insert latex code into the stargazer() output programmatically.

Too long for a comment, so here's a start of an answer. Using the model from the question:
\documentclass{article}
\begin{document}
<<lm, echo=FALSE, message=FALSE, include=FALSE>>=
df <- data.frame(x=1:10, y=rnorm(10))
library(stargazer)
lm1 <- lm(y ~ x ,data=df)
tabular_tt <- function(orig.table) {
library(stringr)
tabular.start <- which(str_detect(orig.table, "begin\\{tabular\\}"))
tabular.end <- which(str_detect(orig.table, "end\\{tabular\\}"))
new.table <- c(orig.table[1:(tabular.start - 1)],
"\\texttt{",
orig.table[tabular.start:tabular.end],
"}",
orig.table[(tabular.end + 1):length(orig.table)])
return(new.table)
}
#
<<print, results='asis', echo=FALSE>>=
cat(tabular_tt(capture.output(stargazer(lm1, label="test"))), sep="\n")
#
\end{document}
You can easily adjust it as necessary. If you're having trouble, I would make sure your target LaTeX syntax is correct by playing with a small toy table in LaTeX only, maybe playing with the tex file generated when you knit.
You may need to make the function cat(new.table, sep = "\n") to get it to get the output correctly into the knitr document.

Related

knitr with octave out.width does not restrict text out runs out of margin

The following is the minimal reproducing example, if you use debian system, one can install octave by snap or apt easily.
\documentclass[english]{article}
\title{Minimal example of octave with knitr for Rnw file}
\author{Xudong Sun}
\begin{document}
\maketitle
<<engine='octave', engine.path='/snap/bin/octave', results='markup', echo=TRUE, out.width=5>>=
x = -10:0.01:10
#
\end{document}
The output text runs out of margin:
Any solutions?
You can simply add the white background ;)
F.e.:
\documentclass[english]{article}
\title{Minimal example of octave with knitr for Rnw file}
\author{Xudong Sun}
\begin{document}
\maketitle
<<chunkName, echo=FALSE, comment=NA, background='#FFFFFF'>>=
x <- rnorm(100)
x
#
\end{document}
... but if you want to save "default dimensions of the bg area" you can use f.e:
<<chunkName, echo=FALSE, comment=NA, background='#FFFF33'>>=
options(width = 60)
x <- rnorm(100)
x
#

R Markdown: visNetWork not displayed in html output when using for loops (or functions)

My visNetwork is not displayed at all when the displaying is attempted in a for loop. In a regular R script, I use the print function and it works just fine, but it does not work in an R Markdown document.
Here is a (hopefully) reproducible example:
---
title: "I want my beautiful networks back!"
---
# First example that works
```{r}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
vn <- visNetwork(nodes, edges, width = "100%")
vn # Or print(vn)
```
# When does it not work?
## In a for loop
```{r}
for (i in 1) vn
```
## In a for loop + using print
This will display the network in the Viewer.
```{r}
for (i in 1) print(vn)
```
## And also in functions
Same remark...
```{r}
foo <- function(x) print(x)
foo(vn)
```
I'm using Rstudio version Version 1.1.383 and
here is the result of a sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6
other attached packages:
[1] visNetwork_2.0.2
I just found a little workaround, consisting the following steps:
Save plot as HTML
Include the HTML code in RMD file
Here an example:
```{r}
for (i in 1:3){
visSave(vn, file = paste0("test",i,".html"))
}
```
```{r, results='asis'}
for (i in 1:3){
cat(htmltools::includeHTML(paste0("test",i,".html")))
}
```
Another solution is to use print(htmltools::tagList())
This prevents the !DOCTOOLS showing in the output.
```{r}
for (i in 1) print(htmltools::tagList(vn))
```
I came across the same issue / solution when working with Datatables and the solution was provided here by #Yihui: https://github.com/rstudio/DT/issues/67
Edit I've since realised that you need at least one visnetwork plotted outside of the loop, i.e. outside of print(htmltools::taglist()), otherwise the script to render is not added to the html file.
You can remove the !DOCTYPE by operating on the string.
cat (as.character(htmltools::includeHTML(paste0("vn",".html"))) %>%
{gsub("<!DOCTYPE html>","",.,fixed = TRUE)} %>%
{sub("\n","",.)}
)
I had the same problem but also wanted to knit my Rmd from the command line, not within RStudio, to easily generate reports for many different parameters, e.g.:
Rscript -e "rmarkdown::render('graphical-res-vis-reports.Rmd', \
params = list(tissue = '${tissue}'), \
output_file = sprintf('graphical-analysis-results_%s.html','${tissue}'))"
The htmltools::includeHTML(html_path) trick worked well when knitting from within RStudio, but it spat out a pandoc error when I tried to knit it from the command line because it's effectively concatenating multiple standalone HTMLs, which does not result in a valid HTML format. (EDIT: the pandoc error may have also been because R from the command line was using a much older version of pandoc than RStudio, but using iframes is still much cleaner.)
I finally found a solution using iframes that works well. Here is a minimal reproducible example:
---
title: "Finally, a way to print visNetworks in a loop!"
---
```{r make networks}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
html_list <- c()
for (i in 1:3){
vn <- visNetwork(nodes, edges)
outfile <- sprintf("vn_%s.html", i)
visSave(vn, file=outfile)
html_list <- c(html_list, outfile)
}
```
```{r plot networks, results="asis"}
for (i in html_list){
print(htmltools::tags$iframe(title = "My embedded document",
src = f, height = "650", width = "900", frameBorder = "0"))
}
```
EDIT: Note that changing the iframe height and width doesn't resize the object from the HTML file. However, you can increase the size of the visNetwork HTML object with a simple text replacement. In this example, I remove the whitespace padding and change the size from 960x500 to 960x960:
visSave(v1, file = out_html)
# adjust browser window size
cmd = sprintf('sed -i \'s|"browser":{"width":960,"height":500,"padding":40,"fill":false}|"browser":{"width":960,"height":960,"padding":0,"fill":false}|\' %s', out_html)
system(cmd)

Plotting with Knitr in Lyx

I'm trying to plot using Knitr in Lyx. When I run
<<>>=
install.packages("ggplot2")
library(ggplot2)
qplot(y=y, x=1:1000, main = 'Log-Likelihood')
#
I get the error
LaTeX Error: File `figure/unnamed-chunk-6.eps.bb' not found.
I've tried including extensions in the starting brackets, but with no success. How do I get my plot?
Following the first answer, tried this:
Defining function (not that important, just to show how I get y)
<<>>=
exp.loglik <- function(lambda, obs){
xbar = mean(obs)
return(length(obs)*log(lambda)-lambda*xbar)
}
#
Defining y (not that important, but just including to show how y is defined)
<<>>=
y = rep(NA,1000)
for (i in 1:1000){
y[i] = exp.loglik(lambda=i/10000, obs=diet_data$survtime)
}
#
Code that runs and then the error occurs (note that I installed the package in pure R as instructed)
<<warning=FALSE, message=FALSE, echo=FALSE>>=
library(ggplot2)
qplot(y=y, x=1:1000, main = 'Log-Likelihood')
#
Same ERROR: LaTeX Error: File `figure/unnamed-chunk-6.eps.bb' not found.
First, install packages separately, just running install.packages in pure R.
Second, you do not define y.
Here's a minimal example that produces a plot without showing R code, warnings or messages:
<<warning=FALSE, message=FALSE, echo=FALSE>>=
library(ggplot2)
qplot(y=10:1, x=1:10, main = 'Log-Likelihood')
#
Edit:
I am running the following code:
<<>>=
exp.loglik <- function(lambda, obs) {
xbar = mean(obs)
return(length(obs)*log(lambda)-lambda*xbar)
}
#
<<>>=
y = rep(NA,5)
for (i in 1:5) {
y[i] = exp.loglik(lambda=i/5, obs=runif(5))
}
#
<<warning=FALSE, message=FALSE>>=
library(ggplot2)
qplot(y=y, x=1:5, main = 'Log-Likelihood')
#
and I get a picture. Is your code working in clean R? Just re-run it to make sure it is. If everything is ok there, then it might be something with the LATEX/knitr installation.

Knitr emptyline after \include graphics

I have a little question, I'm not sure of the cause, but the following knitr code :
<<toto, echo=FALSE, comment=NA, results='asis'>>=
#Data
a<- c(1:100)
b<- c(100:200)
#Plot1
plot(a)
#Plot2
plot(b)
#
produce this LaTeX code :
\includegraphics[width=\maxwidth]{figure/toto1}
(empty line here)
\includegraphics[width=\maxwidth]{figure/toto2}
(empty line here)
How can I remove this empty line?
Use the chunk option fig.show='hold'.

Printing plots generated in a function using R Markdown in RStudio

I am trying to use the R-Markdown feature in R Studio where I was trying to print plots which are generated inside a function. This is a basic run down example of what I am trying to do.
**Test printing plots generated in a function**
================================================
``` {r fig.width=8, fig.height=4, warning=FALSE, eval=TRUE, message=FALSE, tidy=TRUE, dev='png', echo=FALSE, fig.show='hold', fig.align='center'}
dat <- data.frame(x=c(1:10),y=c(11:20),z=c(21:30),name=rep(c("a","b"),each=5))
library(ggplot2)
ex <- function(data){
plot(data[,1],data[,2])
plot(data[,1],data[,3])
}
for (i in 1:10){
t1 <- rbind(i,ex(dat))
}
t1
```
Those testing this code, please make sure to save it as ".Rmd" file and then run the knithtml() in RStudio toolbar. This code above works absolutely fine with the kind of html output I desire. However when I replace the base plotting function by ggplot based code, I cannot get the knithtml() to produce the ggplot output of the 10 plots that I got like before. The base plot code above is now replaced by the following code
p1 <- ggplot(data=data, aes(x=data[,1],y=data[,2]))
p1 <- p1+geom_point()
p1
Am I missing something very simple here.
VJ
There are two problems in your code:
ggplot doesn't recognize the data x and y data, bacause it works inside the data environment. You should give it the column names directly.
The code in yur loop doesn't make sense. You can't mix a plot with an index... (the reason it works with the base plot is through a side-effect) I've replaced it with the simple plot command.
The following will work:
**Test printing plots generated in a function**
================================================
``` {r fig.width=8, fig.height=4, warning=FALSE, eval=TRUE, message=FALSE, tidy=TRUE, dev='png', echo=FALSE, fig.show='hold', fig.align='center'}
dat <- data.frame(x=c(1:10),y=c(11:20),z=c(21:30),name=rep(c("a","b"),each=5))
library(ggplot2)
ex <- function(data){
p1 <- ggplot(data=data, aes(x=x,y=y))
p1 <- p1+geom_point()
return(p1)
}
for (i in 1:2){
plot(ex(dat))
}
```

Resources