Plotting with Knitr in Lyx - r

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.

Related

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)

knitr: knitting chunks with parsing errors

Is it possible to knit chunks with parsing errors?
I want to produce a document explaining some different types of errors one can find while coding in R, but it seems that I can't knit a chunk with parsing error, even with error = TRUE.
For example, this chunk works fine and it shows the error messages:
```{r sum character, error = TRUE}
"1" + "2"
```
However, this chunk doesn't:
```{r missing parenthesis, error = TRUE}
f <- function(x){
z <- sum(x
#
y <- x + 1
return(x + y + z)
}
```
It gives the error: Error in parse(text = x, srcfile = src).
The idea here would be to show all error messages in the chunk "missing parenthesis", is this possible?
This has become possible since the evaluate package >= v0.8.4 (which is expected to be v0.9 on CRAN in the future). For now, you can install evaluate from Github.

new font style for stargazer latex table when using knitr

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.

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

Dynamic references to figures in a R comment within Sweave document

I would like to find a way to use the LaTeX \ref{} markup to comment in the R code within a Sweave .Rnw file. Here are two examples, one in print
http://cm.bell-labs.com/cm/ms/departments/sia/project/nlme/UGuide.pdf
and one to use to work with:
The .Rnw file
% File: example.Rnw
\documentclass{article}
\usepackage{fullpage}
\usepackage{graphics}
\usepackage{Sweave}
\usepackage[margin = 10pt, font=small, labelfont={bf}]{caption}
\begin{document}
Here is an example file to show what I want to do. I would like to figure out how to use the \LaTeX\ reference command to reference a figure being generated by R code. Note in the R code, in a comment there is a reference to the figure, but of course the output file shows a verbatim copy of the \LaTeX\ markup. Does anyone know how to get something for Figure \ref{fig2}?
<< example plot >>=
library(reshape)
library(ggplot2)
n <- 100
lambda <- 1 / 3
x <- seq(0, qexp(0.999, rate = lambda), length = n)
q1.a <- data.frame(x = x,
f = dexp(x, rate = lambda),
F = pexp(x, rate = lambda))
q1.a <- melt(q1.a, id.vars = 'x')
g <- ggplot(q1.a) + # Produces \ref{fig1}
aes(x = x, y = value) +
geom_line() +
facet_wrap( ~ variable, scale = "free_y")
ggsave(g, filename = "example1.jpeg")
#
\begin{figure}[h]
\centering
\includegraphics[width = 0.48\textwidth]{./example1}
\caption{Exponential Distribution based plots.}
\label{fig1}
\end{figure}
Here is more of what I would like to see:
<< example plot 2 >>=
ggsave(g + geom_point(), filename = "example2.jpeg") # Produces Figure 2
#
\begin{figure}
\centering
\includegraphics[width = 0.48\textwidth]{./example2}
\caption{Exponential Distribution based plots with points and lines.}
\label{fig2}
\end{figure}
\end{document}
and the pdf is build with the R commands
Sweave(file = 'example.Rnw',
engine = "R",
keep.source = 'TRUE',
echo = 'TRUE',
results = 'verbatim')
tools::texi2dvi(file = "example.tex",
pdf = TRUE,
clean = TRUE)
Any insight on how do this would be great.
Here is one way to solve this issue by redefining the Sinput environment in which source code is wrapped by Sweave. By default, it is a simple verbatim environment which is not processed by latex for tokens. The trick is to redefine it to use the alltt environment which allows some tokens to be parsed inside the alltt environment. Note that this might lead to unwanted side effects that I am not aware of, so use with caution!
Here is a reproducible example that works. If you compile it, you will generate a file where ref{fig1} is replaced by the figure number.
\documentclass{article}
\usepackage{Sweave}
\usepackage{alltt}
\renewenvironment{Sinput}{\begin{alltt}}{\end{alltt}}
\begin{document}
In this document, we will create a plot using `R`, and reference its position in
the source code.
<<produce-plot, results = hide>>=
pdf('example1.pdf')
plot(1:10, 1:10) # Produces Figure \ref{fig1}
dev.off()
#
\begin{figure}
\includegraphics{example1.pdf}
\caption{Figure 1}
\label{fig1}
\end{figure}
\end{document}

Resources