Knitr - a set of options for a piece * outside * a document?

I am trying to set a global chunk parameter outside my knit call like this:

 opts_chunks$set(dev='pdf') knit(input) 

However, it does not work, since knit seems to use the new set of opts_chunks inside knit .

Is it possible to set the global chunk parameter outside the knit call and apply it to the knit call?


Reason: I am doing this:

I am writing Rmd (R markdown) documents, and I want to be able to knit them with pdf or HTML, my choice is:

 knit2 <- function (input, out=c('pdf', 'html')) { # set the appropriate output image format opts_chunk$set(dev=ifelse(out == 'pdf', 'pdf', 'svg')) # <-- # knit to md o <- knit(input) # knit md to html or pdf pandoc(input=o, format=ifelse(out == 'pdf', 'latex', 'html')) } 

So the idea is that I can knit2('mydoc.Rmd', 'pdf') OR knit2('mydoc.Rmd', 'html') , and I do not need to change Rmd depending on the output .

The problem I ran into was that I want my images to be SVG for HTML output and PDF for PDF output (I need vector graphics, but SVG does not work in Latex, and pdf does not work in HTML, so I you need to change this based on the output format), i.e.

 opts_chunk$set(dev=ifelse(out == 'pdf', 'pdf', 'svg')) 

I know that if I put this in a piece in my Rmd file along with the definition of out , it will work. However, I do not want to embed this in mydoc.Rmd , since I cannot assign output until knit2 is called, I know what result I really want.

Therefore, I want knit2 to somehow set the dev parameter for me before calling knit and apply this option to the duration of knit . (I would also agree to opts_chunk$set(dev=ifelse(out=='pdf', 'pdf', 'svg')) my opts_chunk$set(dev=ifelse(out=='pdf', 'pdf', 'svg')) in my Rmd file, provided that I could define out outside the Rmd file, that is, in knit2 , although if I can handle all of this from knit2 , I would prefer that)

+4
source share
1 answer

You can set global parameters outside the document, and the dev parameter is the only exception. When the HTML output, dev (re) is set to 'png' inside render_markdown() . If you want to change this option, you must call this function before it:

 knit2 <- function (input, out=c('pdf', 'html')) { if (out == 'html') { render_markdown() # use SVG for HTML output opts_chunk$set(dev='svg') } # knit to md o <- knit(input) # knit md to html or pdf pandoc(input=o, format=ifelse(out == 'pdf', 'latex', 'html')) } 

Actually, I had a very similar problem, and this is illustrated in example 084 (see 084-pandoc.R , I changed dev to 'pdf' for Markdown).

+4
source

All Articles