function to get filename without full path in YAML

2019-06-06 09:33发布

问题:

I am trying to modify the behavior of RStudio's knit button, by changing the directory to which it writes the output of knitting the Rmd file. I have started with this answer, but instead of having the filename given by a fixed string, I'd like to have the output filename based on the Rmd filename. However, the variable inputFile includes the full path to the Rmd file. Is there a way to get only the filename without the path?

The header I am working with that produces the full path+filename where I'd like just the filename (test2 is a directory that I created in the current working directory):

---
knit: (function(inputFile, encoding) {rmarkdown::render(inputFile,encoding=encoding, output_file=file.path(dirname(inputFile), "test2", paste0(substr(inputFile,1,nchar(inputFile-4),".html"))) })
output: html_document
---

回答1:

I'm still interested in a command that would directly give me the input filename, as specified in the question, but I found a workaround for the particular issue, using regex in the substr call, based on this:

knit: (function(inputFile, encoding) {rmarkdown::render(inputFile,encoding=encoding, output_file=file.path(dirname(inputFile), "test2", paste0(substr(inputFile,rev(gregexpr("/", inputFile)[[1]])[1]+1,nchar(inputFile)-4),".html"))) })


回答2:

Nowadays, knitr comes with a function current_input() that gives you the name of the Rmd-file as a string. And tools::file_path_sans_ext() will remove the extension.

But to solve the exact problem of the OP, there are probably better options today, for example, knitr options, the package ezknitr, RStudio "Knit Directory" button, or here::here().