R Markdown - variable output name

2019-01-16 11:36发布

问题:

With one R markdown file, I would like to create different possible output pdf documents, where the output file name should be defined within the document. Is there any way to convince markdown to manipulate the output filename in such a way? Ideally I would like to pass the filename by an r chunk.

回答1:

You can keep the simplicity of using the RStudio Knit button and reproducibility of a YAML header by using the undocumented knit hook to redefine what the button does (default function called is rmarkdown::render). The output_file parameter of the render function specifies the file name, so by setting it you override the standard behaviour of using the same prefix as the input filename.

e.g. to always output a file called myfile.pdf

knit: (function(inputFile, encoding) { rmarkdown::render(inputFile, encoding = encoding, output_file = file.path(dirname(inputFile), 'myfile.pdf')) })

The function can be an anonymous one-liner as well as imported from a package, as seen here with slidify.

You can set your own YAML headers (I don't know if this is generally advised anyway), accessible under rmarkdown::metadata$newheader but they don't seem available from within this sort of function as far as I can see.

As for passing file name in from an R chunk... if you're referring to code chunks below the YAML header, from my experience I don't think that's possible(?). Headers can contain inline R commands (single backtick-enclosed, starting with r), but seemingly not for this hook function.

Related:

  • Rmarkdown GitHub repo issue — output format-specific output_file
  • Blog post I wrote following this question on more elaborate uses of the knit: hook / corresponding GitHub wiki notes


回答2:

This is pretty much what I do:

rmarkdown::render('my_markdown_report.Rmd',
                  output_file = paste('report.', Sys.Date(), 
                                      '.pdf', sep=''))

I have three scripts - one pulls the data and process it, second created charts & tables for report. Third one creates report based on markdown file. Code you see above is the part of the third script



回答3:

Following up on what @ilya wrote, this webpage has a great example demonstrating what they are describing, which is how to create multiple, reproducible reports from the same .Rmd document:

http://www.reed.edu/data-at-reed/software/R/markdown_multiple_reports.html

The webpage uses two scripts, one R script and one Rmarkdown script to create multiple reports. I have used it as a template for my own work and found it very useful.