1

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.

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]
}
```

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

teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • 1
    This sounds hard... my understanding (that is, best guess) is that interactively commands are sent to the console for execution by the editor (RStudio, in this case) - so the R session itself has no way of knowing whether the command was copy/pasted, sent by RStudio from some file, typed manually, etc. – Gregor Thomas Sep 21 '20 at 14:05
  • Note, for example, that you can access `YAML` metadata using `rmarkdown::metadata`, but this also won't be available interactively, as the YAML isn't parsed by the interactive R session. And your file might not even be saved yet. I think your best bet might be to define a title/name/id in R code early in the document. – Gregor Thomas Sep 21 '20 at 14:11
  • Yes I was afraid it was going to be hard. I was kind of hoping that since `getwd()` gives different results if executed in a code chunk than at the console, there might be some way to distinguish the console from a code chunk. (At least when the .Rmd doesn't live in the current directory). – teunbrand Sep 21 '20 at 14:14
  • Playing around a bit more, `rstudioapi::getActiveDocumentContext()` seems to know whether it is being executed in a chunk or in the console. The downside is that it reports a path to a temporary file. – teunbrand Sep 21 '20 at 14:25
  • If there's an answer, I think that's the right track. There won't be standard R or even `knitr` commands for this, but `rstudioapi` seems like a good place to start. I mean, RStudio definitely knows what's going on, the question is whether or not that's available to the R session. – Gregor Thomas Sep 21 '20 at 14:30

1 Answers1

2

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

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419