2

In my regular .R script I am using relative paths to read data using rgdal::readOGR:

library(rgdal)
pts <- readOGR("data/points.gpkg")

However the same code in an R snippet in an Rmd doc:

```{r}
pts <- readOGR("data/points.gpkg")
```

returns the following error:

Error in ogrListLayers(dsn = dsn) : Cannot open data source

This error is resolved if I use

```{r}
pts <- readOGR("../data/points.gpkg")
```

But I can't use that path string in a regular .R script. This is frustrating if I want to copy code I wrote in my R script to use in an R markdown document.

I have two questions:

1) Why is this happening?

2) How can I write my paths so they will run in both an .R and a .Rmd document

ASeaton
  • 95
  • 6

2 Answers2

3

An Rmd document's default working directory is the directory it is in. You have a many options:

  • use full file paths (good for you, but not portable to other computers)
  • put your Rmd files in the working directory you're using for your R scripts
  • put your R scripts in the directory with your Rmd files
  • set your working directory in your first Rmd code chunk
  • write your scripts to add a prefix to your filepaths, set the prefix to "./" in your R script and "../" in your Rmd (you could automatically detect this if you want to be fancy)
  • don't duplicate your code: just use scripts or just use Rmd

And many variations like that.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
2

Another solution found at https://github.com/yihui/knitr/issues/277 is to specify the root directory as an option at the top of the document:

opts_knit$set(root.dir = 'path/to/directory')
qdread
  • 3,389
  • 19
  • 36