Knit one markdown file to two output files - r

Is there a way to knit a single .md file to a .html or .docx in the working directory in R and simultaneously post a copy of the .html to another folder, possibly on another drive?
Alternatively, can the 'publish' button in RStudio be used to send a .md file to a location other than RPubs?

Actually, the knit button can indeed -
Render multiple outputs.
Use a custom output directory.
Example with output directory called output:
title: "multiple outputs"
output:
word_document: default
html_document: default
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, encoding = encoding,
output_dir = "output", output_format = "all") })

Yes it's possible to render multiple outputs, but not with the "knit" Button in RStudio. Write your desired output in the YAML header and then use output_format = "all" as argument in
rmarkdown::render(<your-rmd-file.rmd>, output_format ="all")
So the YAML header looks like:
title: "multiple outputs"
output:
word_document: default
html_document: default
Or any option you want to set for the different output formats.
I don't know if it is possible to set different output directories, but I don't think so.

Related

customizing r quarto pdf output file name

How do I customize the filename of r quarto pdf document when I render? Before when I was using Rmarkdown I was using the following code in the YAML:
---
title: "Some title"
author: "First Last"
date: "`r format(Sys.Date(), '%d %B, %Y')`"
output: pdf_document
knit: (function(inputFile, encoding) { rmarkdown::render(inputFile, encoding = encoding, output_file = file.path(dirname(inputFile), paste0(Sys.Date(),"_Report","_FirstLast",".pdf"))) })
---
When I hit the "Knit" button the filename of the pdf document would be 2022-08-08_Report_FirstLast.pdf
Is there a way to do this with quarto pdf? I think the quarto_render function needs to be used but don't know how.
Use the output_file argument of quarto_render function.
file_name = paste0(Sys.Date(),"_Report","_FirstLast", ".pdf")
quarto_render("your_qmd_file.qmd", output_file = file_name, output_format = "pdf")
Now about the approach you are trying,
Firstly, there's no such knit yaml key
in quarto AFAIK
Secondly, although r-code can be used in code-chunk option prefixed be !expr , it's not possible to use inline R code in document yaml section right at this moment of answering this question (03 Sep, 2022). See this discussion on Github.
Though there are some suggested workaround for using r-code in yaml in this discussion on Github, but using quarto_render to control output filename seems the easiest option in your case.
And additionally, if your output file name is simple (that is, without any r-code syntax), you can use output-file yaml option.
---
title: "Testing Output file name"
format:
pdf:
output-file: "output_file_name"
output-ext: "pdf"
---
## Quarto
Quarto enables you to weave together content
and executable code into a finished document.
To learn more about Quarto
see <https://quarto.org>.
## Running Code
When you click the **Render** button
a document will be generated that
includes both content and the output of
embedded code.
This will create the output file named output_file_name.pdf in the directory where the source file is.
If you're comfortable using Quarto CLI in bash shell (which may be more convenient for automatic report generation), you could date-stamp your outputs like this.
now=`date +"%Y-%m-%d"`
quarto render my_doc.qmd --output "./out_$now.pdf" --to pdf

Default knit directory via YAML header in RStudio?

Is there a YAML option, which sets knit directory for an Rmd file? I.e. does the same as illustrated in Fig.1.
The problem is that every time I copy files or share a project with other people (which usually have different default RStudio options than I do), the knit directory should be reset manually in each file.
I'm aware of the global option (Fig.2), but I need a more reproducible solution which works for individual Rmd files in both both RStudio notebook and knitting modes.
And, for instance, I know that there is an option such as:
editor_options:
chunk_output_type: console
Any ideas?
Fig. 1 Setting knit directory via menu commands.
Fig. 2 Global option to set default knit directory in RStudio.
You could try to specify the knit field in the front-matter of our .Rmd file. Example .Rmd that would knit into "some_dir" created in your home directory:
---
title: "Untitled"
output: html_document
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, encoding = encoding, output_dir = "~/some_dir/")
})
---
# Some content
Some content

Multiple sets of Shared Options in R Markdown

Is it possible to have multiple sets of shared options for R Markdown?
This is my problem: I have a folder with a bunch of markdown files. The files can be divided into two groups:
html_document and
revealjs::revealjs_presentation.
I would like to factor out common YAML code from each of these groups. Now I know that I can create a _output.yaml file which would capture common YAML, but I essentially need to have two of these files, one for each of the output formats.
I saw the use of pandoc_args suggested here and I gave it a try as follows:
---
title: Document Type 1
output:
html_document:
pandoc_args: './common-html.yaml'
---
and
---
title: Document Type 2
output:
revealjs::revealjs_presentation:
pandoc_args: './common-reveal.yaml'
---
However using this setup the options from the included YAML files don't get processed.
Any other suggestions would be appreciated!
You can specify multiple output formats in the same _output.yaml file like this (just some example options):
html_document:
self_contained: false
revealjs::revealjs_presentation:
incremental: true
Then you have to render all output formats which cannot be done directly using the RStudio GUI. Instead you have to enter the following into the R console:
rmarkdown::render(input = "your.Rmd",
output_format = "all")
Ideally make sure that there's no output key in the YAML front matter of the .Rmd document itself. Otherwise the output options in _output.yaml file might get overridden. Unfortunately I couldn't find a comprehensive documentation of the exact behavior. Some of my observations so far:
Output options defined in the YAML front matter of the .Rmd document itself always override those specified in the shared options file _output.yaml.
Specifying an output format using the default option set (like pdf_document: default) in the YAML front matter of the .Rmd document itself completely overrides all options specified in _output.yaml. But if you don't explicitly specify the default options (like output: pdf_document; which is only possible for a single output format at once), the _output.yaml content is fully regarded.
If you have specified options for multiple output formats in _output.yaml, only the first one gets rendered when pressing the knit button in RStudio (even if you explicitly press knit to HTML/PDF/Word). You have to use rmarkdown::render(output_format = "all") to render the other formats, too.

rmarkdown: render to .pdf using existing .md files created for .html

Is that possible at all? At the moment I have to render my .Rmd files twice, once for an html and once for a pdf report. Each of them take about 50 mins. So if I can use the html .md files created after rendering, that would save me 50 mins.
You can keep the markdown output of knitr with keep_md: yes
---
output:
html_document:
keep_md: yes
---
Then, using pandoc, you can produce your pdf from this file; in a terminal (not a R console):
pandoc mydoc.md -o mydoc.pdf
You'll have to install pandoc if you haven't already, to use it without knitr.
You might loose a few things, though, because knitr adapts its md intermediary file to the final output.
It is possible to render multiple outputs, but not with the "knit" Button in RStudio. Write your desired output in the YAML header and then use output_format = "all" as argument in
rmarkdown::render(<your-rmd-file.rmd>, output_format ="all")
So the YAML header looks like:
title: "multiple outputs"
output:
pdf_document: default
html_document: default
Or any option you want to set for the different output formats.
If your .md document is already created, you can simply use:
library("rmarkdown")
render("mydoc.md", output_format = "pdf_document")
If you always need to generate both html and pdf, then render both at the same time using J_F's solution.
Alternatively, you can tell the compiler to keep the intermediate .md file. Then, you can easily compile that into other formats.
Go to:
1. RStudio > Open your .Rmd file
2. Click on the Gear (settings) drop down and choose Output Options
3. Choose Advanced
4. Check Keep markdown source file
5. Click OK
6. Knit to HTML
7. Open .md file in editor
8. In Gear (settings) drop down, select PDF as Output Format, AND select (No Preview)
9. In the Preview dropdown, select Preview PDF and a .pdf file should be created
As an alternative to steps 2-5, edit your file so that the header includes:
---
title: "blah blah"
output:
html_document:
keep_md: yes
---

R Markdown - variable output name

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.
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 [invalid link, domain for sale as of 20210216] / corresponding GitHub wiki notes
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
I played around with the Knitr-hook without fully understanding how it works and ran into an ugly workaround. The below coding seems to do the trick.
Would be nice if somebody can either explain why it works and/or if it can written less ugly.
For now I lost the shiny input screen but believe this can even be added later. The good thing is that the R-Studio Knit button can still be used.
Please note that the subtitle and the file name are both: This Works! even with space and exclamation mark. The file is saved as This Works!.pdf
The filename and subtitle are set by assigning the text to the object pSubTitle.
Note that the params are still in the YAML but are not resulting in a shiny popup screen as they are assigned in the Knitr-hook
---
params:
sub_title:
input: text
label: Sub Title
value: 'my_Sub_Title_and_File_Name'
title : "Parameterized_Title_and_output_file"
subtitle : "`r params$sub_title`"
output:
pdf_document:
keep_tex: false
knit: (
function(inputFile, encoding) {
pSubTitle <- 'This Works!'
rmarkdown::render(
input = inputFile,
encoding = encoding,
params = list(sub_title = pSubTitle),
output_file = pSubTitle) })
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. ....
My current solution for this and similar questions is through 2 scripts:
Script1: "xxx.md" file with flexible yaml header, similar to Floris Padt's. This header allows you to generate flexible pdf files with specified title, dates, and other features if you change the params. However, it could not specify flexible pdf names when you render it.
---
params:
feature_input: "XXXA"
date: "08/18/2022"
title: "`Test For `r params$feature_input``"
author: "You Name"
date: "`r params$date`"
output:
pdf_document:
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown and data process
```
#Get parameter from yaml head
input_para <- params$feature_input
input_para
```
Script2: "YYY.R", which specify params in xxx.md file, and specify pdf file names by output_file when rendering.
featureNames <- c("aaa", "bbb", "ccc")
setwd("path to xxx.md")
for (currentFeature in featureNames) {
rmarkdown::render("xxx.Rmd",
params = list(feature_input = currentFeature,
date = Sys.Date()),
output_file=paste0("output/",currentFeature))
}
You could update featureNames in yyy.R file, and run yyy.R to get the most flexible use of your xxx.md file.
This solution allows you to:
update yaml header parameters,
apply updated yaml parameters in your .md code chunk,
and save your pdf with specific and flexible names.

Resources