13

I've written a few functions for a package that use relative paths like:

"./data/foobar.rds"

Here's an example function:

foo <- function(x) { 
x <- readRDS("./data/bar.rds")
return(x)
}

Now, if I were to be working in the development path of the package, this works as I expect. But when I load the package, this path uses the current working directory rather than the relative path of the package.

How does one set it up such that the path for functions within a package maintain their within the package relative paths?

bartektartanus
  • 15,284
  • 6
  • 74
  • 102
Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
  • 1
    See `?system.file` and `?.path.package` – Andrie Aug 15 '12 at 21:18
  • So, something like `x <- readRDS(paste(system.file(package="pkgName"),"/data/bar.rds",sep=""))`? – Brandon Bertelsen Aug 15 '12 at 21:21
  • 1
    If you want something OS independant try x <- `readRDS(file.path(system.file(package = "pkgName"), "data", "bar.rds"))` – dickoa Aug 15 '12 at 21:29
  • If you’re using ‘box’, you can use `box::file()`. If you’re not using ‘box’, and you’re not using packages, there’s no clean solution that always works. The ‘here’ package works in *some* circumstances but not always. – Konrad Rudolph Apr 24 '22 at 21:26

1 Answers1

4

As Andrie notes, you can use system.file, which "finds the full file names of files in packages etc."

x <- readRDS(system.file("help", "aliases.rds", package="MASS"))
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • `dir(system.file("help", package = "MASS"))` – dickoa Aug 15 '12 at 21:31
  • @BrandonBertelsen -- The call to `system.file()` resolves to `/MASS/help/aliases.rds`, which is where the file to be read resides. (All initial unnamed arguments get soaked up by `...`, which `system.file()` treats as a set of subdirectories and files, from which it constructs paths within the given package.) – Josh O'Brien Aug 15 '12 at 21:35