I have a code chunk in an R Markdown file, that generates multiple ggplots in a for loop. The chunk (pseudo-code) is called like so:
```{r print_data, results='asis'}
print.all.results()
```
Inside the print.all.results(), the ggplots are generated and printed using standard print(plot) (see below).
This works without any problems (HTML as well as PDF).
For the PDF outputs, I would now like to switch to landscape mode using \usepackage{pdflscape} (already added to the preamble).
I then tried to switch to the landscape environment in the R code within the chunk. Based on this question and this question, I added the following lines within the print.all.results() function:
cat("\\begin{landscape}")
for (index in vector) {
plot <- generateplot()
print(plot)
}
cat("\\end{landscape}")
However, as soon as I do this, the knitting of the document fails. In the intermediary .tex file, the graphics are not called via \includegraphics anymore but rather, they are linked via the markdown call to them (which of course fails in a tex compile):
\begin{landscape}
![](rmddocument_files/figure-latex/print_data-1.pdf)<!-- -->
![](rmddocument_files/figure-latex/print_data-2.pdf)<!-- -->
![](rmddocument_files/figure-latex/print_data-3.pdf)<!-- -->
\end{landscape}
I have also tried multiple variations using pander but did not find a working solution.
I am now confused why a) the inclusion of the environment suddenly changes the behavior of the print for the plot and b) something comparable seems to work in example 2.
Is this a bug? Could this be a problem with my build pipeline? What could be a solution?
NB: I can't generate the latex code in the .rmd - it has to happen within the code chunk.
An MWE would be this (easiest run trough Knit Button in R Studio; the .tex files and pdfs from the plot are generated in the same folder):
---
title: "Landscape Problem"
author: "Dom42"
date: "`r Sys.Date()`"
output:
pdf_document:
extra_dependencies: pdflscape
keep_tex: yes
---
```{r function}
print.plots.landscape <- function() {
cat("\\begin{landscape}")
for (i in 1:3) {
temp.plot <- plot(hist(mtcars[,i]))
print(temp.plot)
}
cat("\\end{landscape}")
}
```
```{r call, results='asis'}
print.plots.landscape()
```
This Example produces a .tex that contains
\begin{landscape}![](landscape-example_files/figure-latex/call-1.pdf)<!-- --> NULL
![](landscape-example_files/figure-latex/call-2.pdf)<!-- --> NULL
![](landscape-example_files/figure-latex/call-3.pdf)<!-- --> NULL
\end{landscape}
However, what should actually come out of it (works, if uncommenting the cats in the for-loop):
\includegraphics{landscape-example_files/figure-latex/call-1.pdf} NULL
\includegraphics{landscape-example_files/figure-latex/call-2.pdf} NULL
\includegraphics{landscape-example_files/figure-latex/call-3.pdf} NULL
If these three calls would now be enclosed in a landscape environment, I would be happy and my problem would be solved.
The reason you are getting the simple markdown syntax for image insertion after including the landscape environment is because pandoc (the underlying document converter of r-markdown) does not parse the content of latex environments.
To add more details, when you click the knit button of Rstudio, the {knitr} package generates a markdown file containing the markdown syntax for image which as below,
\begin{landscape}
![](landscape-example_files/figure-latex/call-1.pdf)<!-- --> NULL
![](landscape-example_files/figure-latex/call-2.pdf)<!-- --> NULL
![](landscape-example_files/figure-latex/call-3.pdf)<!-- --> NULL
\end{landscape}
And then pandoc is supposed to convert the markdown syntax into latex commands (i.e. \includegraphics), But since pandoc sees the latex environment \begin{landscape}, it doesn't do the conversion and keeps them as is.
So to solve it, we can use the \landscape ... \endlandscape command instead of latex environment (thanks to the informative comment by #samcarter_is_at_topanswers.xyz)
---
title: "Landscape Problem"
author: "Dom42"
date: "`r Sys.Date()`"
output:
pdf_document:
keep_tex: yes
header-includes:
- \usepackage{pdflscape}
---
```{r function}
print.plots.landscape <- function() {
cat("\\landscape\n")
for (i in 1:3) {
temp.plot <- plot(hist(mtcars[,i]))
print(temp.plot)
}
cat("\n\\endlandscape\n")
}
```
```{r call, results='asis'}
print.plots.landscape()
```
Related
I want to use the LaTeX \ovalbox{} command from the fancybox package in an Rmarkdown beamer_presentation, knitted from within RStudio. However, as soon as I add a simple R chunk, I get an "! LaTeX Error: Something's wrong--perhaps a missing \item."
This is a minimum reproducible example:
---
output:
beamer_presentation
header-includes: |
\usepackage{fancybox}
---
## Slide 1
\ovalbox{an oval box}
```{r}
print("x")
```
I can hand-solve the problem afterwards in the .tex file by moving the \usepackage{fancybox} command before the \usepackage{fancyvrb} command which is automatically inserted during the knitting.
Any suggestions how to avoid this problem in the first place?
Seems the packages are fighting over how to mess with verbatim environments.
Normally one could simply load them in a different order, but of course rmarkdown makes such a simple task a lot more complicate. You can make your document compile using this hack (don't try to use any of the verbatim commands from fancybox, this might explode...):
---
output:
beamer_presentation
header-includes: |
\let\VerbatimEnvironmentsave\VerbatimEnvironment
\usepackage{fancybox}
\let\VerbatimEnvironment\VerbatimEnvironmentsave
---
## Slide 1
\ovalbox{an oval box}
```{r}
print("x")
```
I have two RMarkdown files. main.Rmd which is the main file which is rendered as well as example.Rmd which holds a longer example and is used elsewhere (hence it lives in its own document).
I want to include example.Rmd in the main.Rmd file with code highlighting of its RMarkdown code but the code of example.Rmd does not need to be executed, as if I set eval=FALSE and copied all code into the chunk by hand.
An example MWE is
main.Rmd
---
title: This is main.rmd
output: html_document
---
```{r}
# attempt that doesnt work
cat(readLines("example.Rmd"), sep = "\n")
```
and in example.Rmd
---
title: This is example.rmd
output: html_document
---
```{r}
# code that is not executed but shown in main.Rmd
data <- ...
```
Set eval=FALSE in the example.Rmd file and then include it in main.Rmd using child chunk option.
example.Rmd
---
title: This is example.Rmd
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = FALSE)
```
```{r}
# This is from example.Rmd
x <- rnorm(10)
y <- rnorm(10)
lm(y ~ x)
```
```{r}
# some comments
print("This is from example.Rmd")
```
main.Rmd
---
title: This is main.Rmd
output:
html_document:
highlight: haddock
---
```{r example, child="example.Rmd"}
```
Edit
To show full source-code of the Rmarkdown file, one possible option could be reading that Rmd file and then cat it with chunk option comment="".
Now about the syntax highlighting; there's a chunk option class.output with which it is possible to specify a language name for which pandoc supports syntax highlighting.
You can get the list of language names for which pandoc has syntax highlighting support by running the following,
pandoc --list-highlight-languages
(Note, if you don't have pandoc installed separately, you can also use the pandoc installed with Rstudio itself. Run rmarkdown::pandoc_exec() to get the pandoc executable path)
Now, the file we are trying to include actually contains not just R code, but also markdown and yaml syntaxes. So it's a kind of mixed thing and pandoc has no syntax highlighting support out of the box for this. Still I have chosen c as syntax highlighting language just to show the possibility. (Also tried r, but syntax-highlighting is not so distinctive)
---
title: This is main.Rmd
output:
html_document:
highlight: tango
---
## Rmarkdown
```{r example, echo=FALSE, class.output="c", comment=""}
cat(readLines("example.Rmd"), sep = "\n")
```
But still if you want a specific syntax-highlighting for Rmarkdown, you can actually create one. See here from the pandoc documentation itself and also this answer on SO about this.
The following Rmarkdown renders the plotly 3D graph in HTML, but not in PDF.
Testing plotly
```{r}
library(plotly)
p <- plot_ly(data=iris, x=~Sepal.Length, y=~Sepal.Width, z=~Petal.Length,
color=~Species, symbols=c(0,1), type="scatter3d", mode="markers")
p
```
A snapshot of the graph appears as follows:
According to the plotly help page:
If you are using rmarkdown with HTML output, printing a plotly object in a code chunk will result in an interactive HTML graph. When using rmarkdown with non-HTML output, printing a plotly object will result in a png screenshot of the graph.
Is there a way to render the plotly graph in a PDF?
Note: The error from rmarkdown::render() is:
Error: Functions that produce HTML output found in document targeting latex output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:
always_allow_html: yes
Note however that the HTML output will not be visible in non-HTML formats.
I have created a little workaround, which saves the plotly images locally as png-file and imports it back to the RMD file.
You need the package webshot, which you can load via:
install.packages("webshot")
Further more, you need to install phantomjs via
webshot::install_phantomjs()
Then (when phantomjs is in your PATH), you can create your RMD file:
---
title: "Untitled"
output: pdf_document
---
```{r}
library(plotly)
p <- plot_ly(economics, x = ~date, y = ~unemploy / pop)
tmpFile <- tempfile(fileext = ".png")
export(p, file = tmpFile)
```
![Caption for the picture.](`r tmpFile`)
This works for me .. perhaps it's a workaround for you, too!
As #hrbrmstr commented, export() previously didn't support WebGL at all, but more recent versions support exporting to png via RSelenium (see help(export, package = "plotly")). If you need pdf export, you'll have to pay for a cloud account -- https://plot.ly/products/cloud/
Same issue with R markdown compile error:. You need to choose what format you want to KNIT to, tried to look at mine.
---
title: "<img src='www/binary-logo.jpg' width='240'>"
subtitle: "[<span style='color:blue'>binary.com</span>](https://github.com/englianhu/binary.com-interview-question) Interview Question I"
author: "[<span style='color:blue'>®γσ, Lian Hu</span>](https://englianhu.github.io/) <img src='www/ENG.jpg' width='24'> <img src='www/RYO.jpg' width='24'>白戸則道®"
date: "`r Sys.Date()`"
output:
tufte::tufte_html:
toc: yes
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
link-citations: yes
---
What I do so that rendering to PDF's work but you can still have the interactive plots in other knit types and in rmarkdown files in r studio is:
this goes in the setup block (or really, anywhere early in the file):
is_pdf <- try (("pdf_document" %in% rmarkdown::all_output_formats(knitr::current_input())), silent=TRUE)
is_pdf <- (is_pdf == TRUE)
then this is used to render any plotly plot based on what kind of document you are creating:
if (is_pdf) { export(base_plot) } else {base_plot}
in the example base_plot is the name of the plot.
I have been reading about R Markdown (here, here, and here) and using it to create solid reports. I would like to try to use what little code I am running to do some ad hoc analyses and turn them into more scalable data reports.
My question is rather broad: Is there a proper way to organize your code around an R Markdown project? Say, have one script that generates all of the data structures?
For example: Let's say that I have the cars data set and I have brought in commercial data on the manufacturer. What if I wanted to attach the manufacturer to the current cars data set, and then produce a separate summary table for each company using a manipulated data set cars.by.name as well as plot a certain sample using cars.import?
EDIT: Right now I have two files open. One is an R Script file that has all of the data manipulation: subsetting and re-categorizing values. And the other is the R Markdown file where I am building out text to accompany the various tables and plots of interest. When I call an object from the R Script file--like:
```{r}
table(cars.by.name$make)
```
I get an error saying Error in summary(cars.by.name$make) : object 'cars.by.name' not found
EDIT 2: I found this older thread to be helpful. Link
---
title: "Untitled"
author: "Jeb"
date: "August 4, 2015"
output: html_document
---
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
table(cars.by.name$make)
```
```{r}
summary(cars)
summary(cars.by.name)
```
```{r}
table(cars.by.name)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
plot(cars.import)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
There is a solution for this sort of problem, explained here.
Basically, if you have an .R file containing your code, there is no need to repeat the code in the .Rmd file, but you can include the code from .R file. For this to work, the chunks of code should be named in the .R file, and then can be included by name in the .Rmd file.
test.R:
## ---- chunk-1 ----
table(cars.by.name$make)
test.Rmd
Just once on top of the .Rmd file:
```{r echo=FALSE, cache= F}
knitr::read_chunk('test.R')
```
For every chunk you're including (replace chunk-1 with the label of that specific chunk in your .R file):
```{r chunk-1}
```
Note that it should be left empty (as is) and in run-time your code from .R will be brought over here and run.
Often times, I have many reports that need to run the same code with slightly different parameters. Calling all my "stats" functions separately, generating the results and then just referencing is what I typically do. The way to do this is as follows:
---
title: "Untitled"
author: "Author"
date: "August 4, 2015"
output: html_document
---
```{r, echo=FALSE, message=FALSE}
directoryPath <- "rawPath" ##Something like /Users/userid/RDataFile
fullPath <- file.path(directoryPath,"myROutputFile.RData")
load(fullPath)
```
Some Text, headers whatever
```{r}
summary(myStructure$value1) #Where myStructure was saved to the .RData file
```
You can save an RData file by using the save.image() command.
Hope that helps!
Reproducable example:
I am knitting a .rmd document which should show a table of the airquality data frame to a beamer pdf document in RStudio.
.rmd file:
---
title: "Test"
author: "Author"
output:
beamer_presentation:
includes:
in_header: mystyle.sty
---
## Page 1
```{r echo=FALSE, results='asis'}
library(xtable)
print(xtable(airquality), comment=F, tabular.environment='longtable',floating=FALSE)
```
As the data frame is quite long I am using the tabular.environment='long table' option as described here. I am importing in the the .rmd header via mystyle.sty the longtable package, so that the LaTex compilation is prepared.
mystyle.sty:
\usepackage{longtable}
Problem:
The .pdf output is generated without error, but unfortunately the longtable does not work. There's just one page and the table has not been wrapped.
Question:
The target was to get multiple frames (pages) automatically generated fitting the data frame. Any solution to achieve this target?
You can add the latex package to your preamble in the YAML front matter:
header-includes:
- \usepackage{longtable}
This is the only thing I am doing differently and it does work for me.
Also, you might want to add the following options:
,include.colnames=TRUE, include.rownames=FALSE
The first option will repeat the header on each page, the second option will not show the row numbers in the first row.
The problem I'm still having is that it seems to render a { before my table and a } after it.