2

I record individual pieces of my work in R Markdown documents. I have many projects on the go but they tend to overlap, so it is not obvious from reading a document where it originated and therefore where it will be filed on my system.

I can automatically include in a document the folder in which it is filed by inserting:

```{r, echo=FALSE}
 print(getwd())
```

but what I really want to do is automatically include the file name as well as the path to the folder. There is such a feature in MS Word, but is this possible in R Markdown?

These are documents created solely for my own personal use, and therefore storing the full file path is not a problem. Please do not tell me that what I want is inconsistent with reproducibility.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
JeremyC
  • 445
  • 2
  • 14
  • 1
    If you manage your projects with rstudio projects, put your mouse cursor on the opened file tab, it will show the absolute path to the file. – TC Zhang Nov 28 '18 at 06:27
  • 1
    Reproducibility has many levels. One is sending the data and code out to another person. But on the other hand, rerunning the same code by the creator a few weeks, months or years later is equally important. Not sure if the solution will be brainless, but using [here::here](https://stackoverflow.com/questions/32728981/function-to-get-filename-without-full-path-in-yaml-header-of-rmarkdown-document) could perhaps work out to some degree? – Roman Luštrik Nov 28 '18 at 06:49

1 Answers1

4

The function knitr::current_input() will return the name of the current R Markdown file, as explained here. You could combine this with the working directory as follows:

knitr::current_input(dir = TRUE)

Note, this will only properly work when you knit the document. It will return NULL if you try and run it within RStudio.

If you wanted an easy way of including this within your analysis, you could add the filepath as a subtitle to your document by including it in your YAML:

---
title: Your Document
subtitle: "`r knitr::current_input(dir = TRUE)`"
output: word_document
---
Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • Many thanks. That works very well. (I was a bit puzzled by your edits to my question though; they seemed purely stylistic) – JeremyC Nov 28 '18 at 11:14
  • 3
    I'd recommend `knitr::current_input(dir = TRUE)` instead of `file.path(getwd(), ...)` since `getwd()` is subject to user's changes. – Yihui Xie Nov 28 '18 at 14:49
  • Thanks @YihuiXie! I thought this was a bit sloppy at the time but I didn't think to check the documentation. Updated the answer – Michael Harper Nov 28 '18 at 14:52