What does Work
I am able to make the subtitle of my pdf file dynamic based on user input. I am also able to generate a 'semi-dynamic' file name using the subtitle field from the YAML (the working code is given below)
What doesn't Work
However I am not able to do both, being a subtitle and output file which are based upon the users input.
As rmarkdown::yaml_front_matter(inputFile)$title does work I tried to use rmarkdown::yaml_front_matter(inputFile)$subtitle however it seems to have the unevaluated r-code.
A long shot was rmarkdown::yaml_front_matter(inputFile)$params$sub_title but that resulted in an error. I don't know if the params are set already and even accessible with this function.
Related questions
- Using a YAML header argument in knitr
- R Markdown - variable output name
- Setting document title in Rmarkdown from parameters
Code
---
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) {
rmarkdown::render(
input = inputFile,
encoding = encoding,
params = 'ask',
output_file = file.path(
paste0(rmarkdown::yaml_front_matter(inputFile)$title, '.pdf'))) })
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. ....
The code above does work as it refers to the static yam field title.
Replacing title by subtitle will fail as will using params$subtitle
UPDATE: Best Workaround (so far)
Today 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. ....
来源:https://stackoverflow.com/questions/56622368/how-to-base-the-output-file-name-and-sub-title-on-user-input-using-params
