yihui / knitr

A general-purpose tool for dynamic report generation in R
https://yihui.org/knitr/
2.39k stars 878 forks source link

Specify output directory path #1728

Open ghost opened 5 years ago

ghost commented 5 years ago

Currently the knit function specifies an output path that may include a directory, such as:

knit( "filename.Rmd", "build/filename.md" )

Being able to specify the output directory alone would be convenient when knitting multiple files. Such as:

knit( "01.Rmd", "build/" )
knit( "02.Rmd", "build/" )

This would produce ./build/01.md and ./build/02.md, thereby eliminating some minor code duplication. (The trailing slash could be used to denote a directory; otherwise, knit could check to see if the build parameter already exists as a directory before trying to write it as a regular file. In the case that the specified path is a directory that exists, knit would export the file into said directory.)

ghost commented 5 years ago

For context, I'd like to write the following, which is fairly self-explanatory:

file.yaml <- paste( args[1] )
file.rmd <- paste( args[2] )
dir.artefacts <- paste( args[3] )
knit( file.rmd, dir.artefacts )

Instead, the following is required:

file.yaml <- paste( args[1] )
file.rmd <- paste( args[2] )
dir.artefacts <- paste( args[3] )
file.md <- paste0( 
  paste( sep='/',
    dir.artefacts,
    file_path_sans_ext( file.rmd )
  ), '.md' )
knit( file.rmd, file.md )

The code to generate the filename of file.md within the artefacts directory is likely fairly analogous to code that already exists inside the knit function (with respect to manipulating the destination filename).

cderv commented 5 years ago

FWIW, I think this is implemented in rmarkdown::render. Did you try this ?

rmarkdown::render(file.rmd, output_dir = dir.artefacts)

I often use rmarkdown and not knitr directly with rmd files. I was wondering if this answer your needs. :thinking:

ghost commented 5 years ago

I was wondering if this answer your needs.

It would have if the package didn't create temporary files in the directory being monitored for the creation of or updates to Markdown files using inotifywait. Although I could ignore .knit.md and .utf8.md files, it isn't a very clean solution. (That is, there could be other temporary files created or end-users could actually name some of their files with a .knit.md extension, which I'd have to tell them not to do and then explain why...)

Creating a temporary directory for the intermediates_dir parameter could be another solution, but that's still extra complexity --- pretty much equivalent to parsing out the file name extension but with an I/O performance hit and the introduction of cross-platform temporary directory creation (and permissions) concerns.

Thank you, though, it would have otherwise worked.