Alex Holcombe
Alex Holcombe

Reputation: 2593

Can I conditionally exclude some elements (code blocks) from rendering to the PDF and ePub outputs when compiling a bookdown document?

RMarkdown knitting creates beautiful html, including animated gifs with R codeblocks like:

{r, echo=FALSE, out.width="80%", fig.cap=""}
knitr::include_graphics(path="imagesForRmd/visualSearch/directionOfMotionPopsOut.gif")

While such codeblocks work for including images other than gifs in the PDF output of bookdown, animated gifs unsurprisingly yield an error:

Cannot find the file(s): "(imagesForRmd/visualSearch/directionOfMotionPopsOut.gif"

Is there a way to conditionally exclude specific content in my .Rmd files, such as the above codeblock, from the pdf_book and ePub rendering, so that the error does not occur? Then I could create the html version with the animated gifs, and the PDF and ePub without.

Upvotes: 1

Views: 277

Answers (2)

Martin C. Arnold
Martin C. Arnold

Reputation: 9668

I think it's more idiomatic to do this using the chunk option eval. As already mentioned, using knitr you may check the output format on knitting. Since epub is considered an HTML output format you may do it like this:

```{r, eval = knitr::is_html_output(excludes = "epub")}
knitr::include_url(path = "your_image.gif")
```
```{r, eval = knitr::is_latex_output()}
knitr::include_graphics("your_image.png")
```

Upvotes: 3

jackdougherty
jackdougherty

Reputation: 177

One solution is to write an if/else statement to display the animated GIF in the HTML book, and display a static PNG image in the PDF and other books:

if(knitr::is_html_output()) knitr::include_url("images/sample.gif", height = "250px") else knitr::include_graphics("images/sample.png")

Upvotes: 2

Related Questions