数获取RMarkdown文档的YAML标头中没有完整路径的文件名

数获取RMarkdown文档的YAML标头中没有完整路径的文件名

本文介绍了函数获取RMarkdown文档的YAML标头中没有完整路径的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过更改RStudio编织按钮的行为,更改其写入编织Rmd文件的输出的目录.我从此答案开始,但是我不想使用固定字符串给出的文件名,而是使用根据Rmd文件名输出文件名.但是,变量inputFile包含Rmd文件的完整路径.有没有办法只获取文件名而没有路径?

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?

我正在使用的标头会生成完整的路径+文件名,而我只需要文件名(test2是我在当前工作目录中创建的目录):

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
---

推荐答案

如今,knitr附带了一个函数current_input(),该函数为您提供Rmd文件的名称作为字符串.然后tools::file_path_sans_ext()将删除扩展名.

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.

但是要解决OP的确切问题,今天可能有更好的选择,例如,编织器选项,软件包 ezknitr ,RStudio"编织目录" 按钮 here::here() .

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().

这篇关于函数获取RMarkdown文档的YAML标头中没有完整路径的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:57