knitr: how to set package options depending on out

2020-03-03 08:24发布

问题:

I am starting to use package knitr as a component in the workflow to produce HTMLand PDF reports from a Markdown input file.
I would like to set some knitr package options specifically tailored to the format of the output file. Currently I manually switch back and forth the following two lines:

<!--roptions dev='png', fig.width=300px, fig.height=200px" -->
<!--roptions dev='pdf', fig.width=5, fig.height=4 -->

Is it possible to let knitr know which set of options to use based on output type, automatically?

Thank you.

回答1:

@Ramnath comment suggests a solution to producing pdf and html output from a unique Markdown file by setting specific options to knitrin the Makefile:

$(PDF): $(SRC) Makefile
Rscript \
  -e "library(knitr)" \
  -e "opts_chunk[['set']](dev = 'pdf')" \
  -e "pat_gfm()" \
  -e "knit('$<', 'temp.md')"
$(PANDOC) temp.md -o $@
rm temp.md

Here the format of images is set to pdf. Note that the pat_gfm() function has been added in the master branch on GitHub just 5 days ago and has not been released as a stable version yet.

Elaborating a bit to fully answer the question, the image dimensions can be easily setted by adding a couple of lines to the Makefile:

-e "opts_chunk[['set']](fig.width = 5)"\
-e "opts_chunk[['set']](fig.height = 5)"\


标签: r knitr