Dynamic output filenames: Name the pdf after a variable from r code chunk in rmd body. Is there any solution?

Hello everyone, I would like to give my pdf file a dynamic file name. I already found out that you can name it after the current Sys.Date(), but naming the file after the data being processed in the script is somehow not possible.. Although the document title can be named dynamically by just creating a second YAML section below the R code chunk, where the data is being processed. It does not work with the output file name.

The dynamic title is working fine. But my code to name my file dynamically after the nrows of the given dataframe does not work and is just ignored. Is there any solution to this problem?

output: pdf_document

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)


title: "An analysis of `r nrow(x)` cars"
knit: (function(inputFile, encoding) {rmarkdown::render("try.Rmd", output_file=paste("report-", nrow(x), ".pdf", sep=""))})

Thank you so much in advance.

I don't think the knit: hook works outside of the first YAML header. A workaround is to put the call to rmarkdown::render() in a wrapper script.

Yes, knit: field is a trick as this is used by RStudio IDE to modify the behavior of the render button by passing a custom function.

I don't think there is an easy way to name your output file from within the code of you rmarkdown. A wrapper that will render and then rename the output based on some information (written in a file by your Rmd document content ?) seems the easiest solution

1 Like

Dear Alexis and Christophe,

A wrapper script worked for me! Thank you a lot!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.