mathematical.coffee
mathematical.coffee

Reputation: 56955

knitr - set chunk options *outside* document?

I'm trying to set a global chunk option outside my call to knit like so:

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

However, it isn't working, as knit seems to use a fresh set of opts_chunks within knit.

Is it possible to set a global chunk option outside a call to knit, and have it apply for the call to knit?


Reason I'm doing this:

I'm writing Rmd (R markdown) documents, and I want to be able to knit these to pdf or HTML, my choice, like so:

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 don't have to change the Rmd depending on the output.

The problem I encountered was that I want my images to be SVG for HTML output, and PDF for PDF output (I wanted vector graphics but SVG doesn't work in Latex, and pdf doesn't work in HTML, so I need to modify 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 chunk in my Rmd file along with a definition of out, it will work. However, I don't want to embed this within mydoc.Rmd, as I can't assign output until knit2 is called an I know what output I actually want.

Hence, I want knit2 to somehow set the dev option for me before calling knit and have that option apply for th duration of the knit. (I would also accept embedding my opts_chunk$set(dev=ifelse(out=='pdf', 'pdf', 'svg')) into my Rmd file, provided that I could define out outside the Rmd file, i.e. in knit2, although if I can handle it all from knit2 I'd prefer that)

Upvotes: 4

Views: 530

Answers (1)

Yihui Xie
Yihui Xie

Reputation: 30194

It is possible to set global options outside a document, and the dev option is the only exception. When the output is HTML, the dev is (re)set to 'png' internally by render_markdown(). If you want to change this option, you have to 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 have had a very similar problem, and illustrated this in the example 084 (see 084-pandoc.R there; I changed dev to 'pdf' for Markdown).

Upvotes: 4

Related Questions