Search code examples
rpackagedevtools

Dynamically determine name of current package


I am developing an R package and in one of my functions I want to access files which are in the inst/ folder (in the source code). When this package is eventually installed, folders in inst/ are moved to the base directory of the package.

Thus, if I want to access the file inst/foo/bar.css I would use

myfun <- function() {
   ## ...
   system.file("foo", "bar.css", package = "mypackagename")
   ## ...
}

This requires, however, hardcoding the name of the package. If, for whatever reason, the name of the package changes later, I would need to change these values as well.

I could think of the following workaround:

myfun <- function() {
   ## ...
   system.file("foo", "bar.css", package = environmentName(parent.env(environment())))
   ## ...
}

but I am not sure whether this will work in all cases.

Hence, my question, what is the most reliable way to access a file in the same package?


Solution

  • The devtools package is very heavy on dependencies.

    Actually, devtools relies on the pkgload package to get the package name, so you could save yourself the overhead (especially useful in e.g. GiHub Actions) and just run:

    pkgload::pkg_name(".")
    #> [1] "mypackage"
    
    # or simply:
    pkgload::pkg_name()
    #> [1] "mypackage"