Cannot create PDF from R Markdown without template file lines - r

I am trying to create a long document in R Studio using R Markdown to PDF, and I am getting the following error when I push the "Knit PDF" button:
! Undefined control sequence.
l.124 \begin{center}\includegraphics
pandoc.exe: Error producing PDF from TeX source
Error: pandoc document conversion failed with error 43
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Execution halted
I am able to properly create the PDF if I make a new R Markdown document and I paste the code in from the original, provided I keep the following code at the end of the new document. When I erase this code, I get the above error.
```{r, echo=FALSE}
plot(cars)
```
I have no need or desire for the cars plot to be in my document. I am able to Knit this document into HTML without the undesired code, but not to PDF. Can anyone advise why this error may be happening? (This is my first post to this forum, so if you need more specific information, please advise).
I am running Windows 7 32 bit, R Studio version 0.98.1103, MiKTeX version 2.9.
Edit/Update: Here is my code, including the cars graph which I do not want.
---
title: "Untitled"
date: "Saturday, April 25, 2015"
output: pdf_document
---
```{r echo=FALSE, warning=FALSE, include=FALSE}
require(qcc)
require(data.table)
require(ggplot2)
require(sm)
require(knitr)
require(xtable)
attach(airquality)
airquality$indicator <- ifelse(airquality$Month < 8,'Classic','New')
```
```{r echo=FALSE, warning=FALSE, results='hide', fig.align='center'}
par(mfrow=c(2,1), oma=c(1,1,1,1), cex=.5, mex=.5, ps=8, mgp=c(3,1,0))
airquality <- airquality[complete.cases(airquality),]
# Plot variable on an SPC chart of type xbar.one
imrchart2 <- qcc(airquality$Ozone[airquality$indicator=="Classic"], "xbar.one", std.dev="SD", add.stats=TRUE, ylab="Ozone", title="Xbar.One Chart for Ozone", xlab="", data.name="Classic", restore.par=FALSE, newdata=airquality$Ozone[airquality$indicator=="New"], newdata.name="New", ylim=range(airquality$Ozone))
# Plot a CUSUM chart
cusum(airquality$Ozone[airquality$indicator=="Classic"], sizes=1, add.stats=TRUE, ylab="Ozone", title="CUSUM Chart for Ozone", xlab="", restore.par=FALSE, newdata=airquality$Ozone[airquality$indicator=="New"], data.name="Classic", newdata.name="New")
```
```{r, echo=FALSE}
plot(cars)
```

Related

Render ggplotly() in R Markdown github_document

Interactive graphs created with ggplotly() go along nicely with html_document output in R Markdown, see eg. RMarkdown and ggplotly. For github_document output, however, the knitted HTML preview file does not show ggplotly() graphs.
I adopted the code from the linked SO post and only changed the output format in the header. Does anyone know how to render plotly graphs correctly with this kind of output? Or at least, if that is even possible?
---
title: "RmarkdownExample"
author: "fdetsch"
date: "April 16, 2020"
output: github_document
---
Here is the graph I generated.
```{r setup, message = FALSE, echo = FALSE, warning=FALSE}
# Require
library(plotly)
# Create
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
# Plot
g <- qplot(carat, price, data=dsamp, colour=clarity)
# Call
ggplotly(g)
```
For output: github_document, I found a workaround that renders ggplotly() graphs nicely using iframes. The trick is to export the plotly widget as HTML and subsequently embed it as iframe. In my opinion, the advantage over output: html_document with keep_md enabled is that the online .md file simply prints a link to the intermediary HTML file instead of the full widget code, making it much tidier.
---
title: "Render `ggplotly()` graphs in `github_document`"
author: "fdetsch"
date: "`r Sys.Date()`"
output: github_document
---
Here is the graph I generated.
```{r setup, message = FALSE, echo = FALSE, warning = FALSE}
# Require
library(plotly)
# Create
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
# Plot
g <- qplot(carat, price, data=dsamp, colour=clarity)
# Call
p <- ggplotly(g)
```
```{r include, echo = FALSE}
htmlwidgets::saveWidget(p, "index.html")
htmltools::tags$iframe(
src=file.path(getwd(), "index.html"),
width="100%",
height="600",
scrolling="no",
seamless="seamless",
frameBorder="0"
)
```
At least when opening the preview HTML in an external viewer, the interactive graph shows up. The RStudio (preview version 1.3.938) viewer currently fails to render the image.
There seem to be some problems with github_document, see here. My workaround: knit to html_document and save the resulting *.md-file.
So the YAML header is:
---
title: "RmarkdownExample"
author: "fdetsch"
date: "April 16, 2020"
output:
html_document:
keep_md: true
---
You can then use the md file to upload to github.

How to use RStudio to write R Markdown files with Stata graphs?

The code below works for Stata commands and output but does not produce the graphs:
---
title: "Stata and R Markdown (Windows)"
author: "Doug Hemken"
date: "July 2015"
output:
html_document:
toc: yes
---
```{r, echo=FALSE, message=FALSE}
require(knitr)
statapath <- "/Applications/Stata/StataSE.app/Contents/MacOS/stata-se"
opts_chunk$set(engine="stata", engine.path=statapath, comment="")
```
### Descriptive Statistics
A simple example.
```{r}
sysuse auto
summarize
```
```{r}
sysuse auto
twoway (scatter mpg weight)
```
Note that this is a follow-up of this question:
How to use RStudio to write a RMarkdown file with Stata commands?.
You need to export the graph and include an image link in the R Markdown as follows:
```{stata, echo=1, results="hide"}
twoway (scatter mpg weight)
graph export "myscatter.svg", replace
```

Remove progress bar from knitr output

I'm analyzing some data and would like to do a Simpsons paradox on R. I've installed the Simpsons package and loaded the library. Here is an example based on the package documentation:
---
output: html_document
---
```{r}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
This is returning a plot with 3 clusters (exactly what I need). However, when I Knit the Rmd file to HTML, I'm getting a lot of equals signs (======) with a percentage next to it like a loading grid which I would like to remove from my final output.
You can suppress any output messages in R by setting the knitr chunk option. If we wish to hide all code output other than plots, we can use the following solution:
---
output: html_document
---
```{r echo=FALSE, results='hide', fig.keep='all', message = FALSE}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
I would note that this package seems to print out a lot more content that most packages, and therefore the combination of options are quite long.
An easier method would probably be to move the plot to a separate chunk and have all the analysis run before it. The include argument can be used to suppress all outputs, but this includes plots, hence why we must use two chunks:
```{r, include = FALSE}
# your code to build model
```
```{r}
plot(example)
```
Check out the full list of knitr chunk options here

Printing graph to a PDF file apart and a R Markdown output at same time

Supposing if I have this function to print a plot in a PDF file:
generatePlot<-function(values) {
pdf(file = "foo.pdf")
barplot(values, main = "A simple example")
dev.off()
}
And then I am doing this in a "test.Rmd", parameterizing r warning=FALSE, message=FALSE, echo=FALSE, that will output a PDF document:
tmp.values <- sample(10, 6)
generatePlot(tmp.values)
The problem is: plot just is appearing on "foo.pdf" and not on "test.pdf".
In the second one, I observe only the following:
## pdf
## 2
What do I have to do for the plot to be printed in both files?
Try the following:
---
title: "My HTML page"
output: pdf_document
---
```{r, warning=FALSE, message=FALSE, echo=FALSE}
generatePlot<-function(values) {
barplot(values, main = "A simple example")
dev.copy(pdf, "foo.pdf")
invisible(dev.off())
}
```
```{r warning=FALSE, message=FALSE, echo=F}
generatePlot(mtcars$mpg)
```
As you can see I am using dev.copy instead to make sure that the plot is printed on the default device first and then copied to the pdf device which saves the plot at the location of the Rmd document. In order to suppress the output of dev.off() use invisible().

R Markdown: plots within a loop going out of margin when typesetting to PDF

When typesetting an R Markdown document to PDF, if a function draws multiple plots, those plots often appear side-by-side, with only the first plot fully within the margins of the page.
Minimal R Markdown example:
---
title: "Example re plotting problem"
author: "Daniel E. Weeks"
date: "May 3, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Multiple plots within a loop
```{r}
plots <- function() {
plot(rnorm(100))
hist(rnorm(100))
}
for (i in 1:3) {
plots()
}
```
Here is a screenshot of page 2 of the generated PDF
which shows the problem. I have searched online, but haven't yet found a solution to this problem.
Thank you.
The plot hook solution proposed by user2554330 is simple and works well. So this code draws all the plots within the margins of the resulting PDF:
---
title: "Example re plotting problem"
author: "Daniel E. Weeks"
date: "May 3, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Multiple plots within a loop
```{r}
plots <- function() {
plot(rnorm(100))
hist(rnorm(100))
}
```
## Call plotting function
```{r}
my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)
for (i in 1:3) {
plots()
}
```
The problem is that the generated .tex file has no spaces between the \includegraphics{} calls. LaTeX gives warnings about overfull hboxes, because the graphics aren't big enough to sit alone on a line, and are too big when it puts two on each line.
You can tell LaTeX (TeX really) to output the bad lines without putting two figures on each line by adding
\pretolerance=10000
in the text before the code chunk. You'll probably want to set it back to its default value
\pretolerance=100
after the code chunk, or LaTeX won't try hyphenation afterwards, and text can look really ugly.
Another way to fix this would be to force each figure to be in its own paragraph. You can do this by adding this code
my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)
into a code chunk before you do your plotting. This puts a blank line
before and after each figure.

Resources