Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr: include figures in report *and* output figures to separate files

Not only would I like my figures to appear in my knitr-generated report, but I would also like to output them to separate files, too. To do this, I have included code like the following:

```{r}
  #Plot figure in report
  plot(x,y)

  #Plot figure in file
  pdf(file="MyFig.pdf")
  plot(x,y)
  dev.off()
```

This works fine, but I expect there's a more elegant solution for this already built into knitr. Is there a chunk option or something similar that achieves the same results?

like image 946
Lyngbakr Avatar asked Jan 16 '15 20:01

Lyngbakr


People also ask

What is knitr used for?

knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.

How does R knitr work?

When you run render , R Markdown feeds the . Rmd file to knitr, which executes all of the code chunks and creates a new markdown (. md) document which includes the code and its output. The markdown file generated by knitr is then processed by pandoc which is responsible for creating the finished format.

What is a knitr document?

knitr is an R package that integrates computing and reporting. By incorporating code into text documents, the analysis, results and discussion are all in one place.

How do I hide the output of a chunk in R markdown?

You use results="hide" to hide the results/output (but here the code would still be displayed). You use include=FALSE to have the chunk evaluated, but neither the code nor its output displayed.


2 Answers

Use the option self_contained: no if you are using html_document, or keep_tex: yes if you use pdf_document, so that rmarkdown will not remove the figure files after rendering the output document.

like image 138
Yihui Xie Avatar answered Sep 27 '22 15:09

Yihui Xie


Keyword dev='pdf' as explained by Yihui here http://yihui.name/knitr/options/

Together with other options I have found useful:

```{r 'setup', echo = FALSE, cache = FALSE}
    opts_chunk$set(dev = c('pdf', 'png'), 
        fig.align = 'center', fig.height = 5, fig.width = 8.5, 
        pdf.options(encoding = "ISOLatin9.enc")) 
```
like image 36
PatrickT Avatar answered Sep 27 '22 16:09

PatrickT