Search code examples
rr-markdownrgdalogr

relative paths using readOGR are different depending on whether R script or rmarkdown


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


Solution

  • 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')