Suggestion for a chunk to automatically execute knitr in the same .rmd file

Hi there,
not sure if posting this is ok, as it´s not a question, but rather a solution. But since I didn´t find the solution anywhere else, it might help others with similar problems. Or others might suggest better solutions.

The chunk below can be added at the end of a script to then automatically knit the document when using "run all". Sure, pressing the button isn´t difficult, but with scripts that take a while to complete, it´s more convenient if the knit is initiated at the end of the script.

This solution solves this error:
Error in parse_block(g[-1], g[1], params.src) : duplicate label 'setup'
-> it seems this problem occurs because knitr will be called again when knitr is running the script as part of the knitting process. Hence, the solution was to limit execution of the chunk to cases when knitr isn´t running by using this option eval = !isTRUE(getOption(''))

Also, not using the "knit" button but the function call allowed using a file name generated during run-time to save the knit output.

#``` <- didn´t know how to keep those"```", # must be removed...
{r, automaticKnitting, echo = FALSE, eval = !isTRUE(getOption(''))}

#loading stringr for string editing of file names and paths
if (!require("stringr")){ 

#dynaically getting the file name during runtime, in case the .rmd file was saved with a different name
RMD_fileName <- str_replace(rstudioapi::getActiveDocumentContext()$path, paste0(sub("\\/[^\\/]*$", "",rstudioapi::getActiveDocumentContext()$path),"/"),"")

#fileName is the file name of data that was loaded (somewhere else in the script) - will be appended for output
fileName <- "FileName.txt" 

#using fileName and appending it by _OVERVIEW
outputFileName <- paste0(str_replace(fileName,".txt",""), "_OVERVIEW")

  rmarkdown::render(input = RMD_fileName, output_file = outputFileName)
#```<- didn´t know how to keep those"```", # must be removed...