交互模式下的自引用Rmd文件 [英] Self-reference Rmd file in interactive mode

查看:44
本文介绍了交互模式下的自引用Rmd文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm interested in attaching metadata to saved objects, including the script that saved the data. Towards that end, I would like to catch the name of a script in the script itself.

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

When I have an Rmarkdown document as below and I knit it, the code chunk results in the name of the script that generated it. This is exactly what I want, however, this only works when the document is being knit. I would like to do the same if I'm executing the chunk in Rstudio in an interactive way.

---
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脚本的名称吗?

Does anybody know how to catch the name of the current Rmarkdown script in an interactive session?

推荐答案

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

rstudioapi::getSourceEditorContext() gives you information (a list) about the current file opened in the RStudio source editor. The path of the file is stored in the path element of the list.

BTW,对于非交互式R会话, knitr :: current_input()为您提供了要编织的源文档的路径(您的 sys.call(1)不过,这种方法听起来很聪明.

BTW, for non-interactive R sessions, knitr::current_input() gives you the path to the source document being knitted (your sys.call(1) approach sounds clever, though).

这篇关于交互模式下的自引用Rmd文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆