交互模式下自引用 Rmd 文件

Self-reference Rmd file in interactive mode

我有兴趣将元数据附加到保存的对象,包括保存数据的脚本。为此,我想在脚本本身中捕获脚本的名称。

当我有一个如下所示的 Rmarkdown 文档并编织它时,代码块会生成生成它的脚本的名称。这正是我想要的,但是,这仅在编织文档时有效。如果我以交互方式在 Rstudio 中执行块,我想做同样的事情。

---
title: "test"
author: "me"
date: "21/09/2020"
output: html_document
---

```{r}
if (interactive()) {
  # Get the same as non-interactive version?
} else {
  as.character(sys.call(1))[2]
}
```

有人知道如何在交互式会话中捕获当前 Rmarkdown 脚本的名称吗?

rstudioapi::getSourceEditorContext() 为您提供有关在 RStudio 源代码编辑器中打开的当前文件的信息(列表)。文件的路径存储在列表的 path 元素中。

顺便说一句,对于 non-interactive R 会话,knitr::current_input() 为您提供了正在编写的源文档的路径(不过您的 sys.call(1) 方法听起来很聪明)。