-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathrmarkdown.Rmd
71 lines (52 loc) · 2.27 KB
/
rmarkdown.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
---
title: "Using here with rmarkdown"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Using here with rmarkdown}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
error = !identical(Sys.getenv("IN_PKGDOWN"), "true")
)
project_path <- system.file("demo-project", package = "here")
```
The here package enables easy file referencing by using the top-level directory of a file project to easily build file paths.
This article demonstrates the case where the working directory is set to a subdirectory of the project root, for instance when rendering an R Markdown document that lives in a subdirectory.
See `vignette("here")` for a more general introduction.
## rmarkdown starts in a subdirectory
For demonstration, this article uses a data analysis project that lives in `` `r project_path` `` on my machine.
This is the *project root*.
The path will most likely be different on your machine, the here package helps deal with this situation.
The project has the following structure:
```{r echo = FALSE}
fs::dir_tree(project_path)
```
When `report.Rmd` is rendered, the working directory is internally set to `<project root>/analysis` by rmarkdown:
```{r eval = FALSE}
setwd(file.path(project_path, "analysis"))
```
```{r include = FALSE}
knitr::opts_knit$set(root.dir = file.path(project_path, "analysis"))
```
```{r}
getwd()
```
However, `penguins.csv` still lives in the `data/` subdirectory.
The report requires the `penguins.csv` file to work.
## here always uses project-relative paths
To render `report.Rmd`, you would have to ensure the path to `penguins.csv` is relative to the `analysis/` directory - i.e., `../data/penguins.csv`. The chunks would knit properly, but could not be run in the console since the working directory in the console *isn't* `analysis/`.
The here package circumvents this issue by always referring to the project root:
```{r}
here::i_am("analysis/report.Rmd")
```
All files accessed by `report.Rmd` should be referred to using `here()`:
```{r}
library(here)
here("data", "penguins.csv")
here("data/penguins.csv")
```
This ensures that `penguins.csv` can be read both when the report is knit and when the code is run interactively in the console.