This package helps accessing files relative to a project root to stop the working directory insanity. It is a low-level helper package for the here package.
library(rprojroot)The rprojroot package works best when you have a "project": all related files contained in a subdirectory that can be categorized using a strict criterion. Let's create a package for demonstration.
# A fixed name, so the demo package is not called `file1a2b3c` in the output.
dir <- file.path(tempdir(), "demopkg")
pkg <- usethis::create_package(dir)
#> ✔ Creating /tmp/RtmpXXXXXX/demopkg/.
#> ✔ Setting active project to "/tmp/RtmpXXXXXX/demopkg".
#> ✔ Creating R/.
#> ✔ Writing DESCRIPTION.
#> Package: demopkg
#> Title: What the Package Does (One Line, Title Case)
#> Version: 0.0.0.9000
#> Authors@R (parsed):
#> * Kirill Müller <kirill@cynkra.com> [aut, cre] (ORCID: <https://orcid.org/0000-0002-1416-3412>)
#> Description: What the package does (one paragraph).
#> License: MIT + file LICENSE
#> Encoding: UTF-8
#> Roxygen: list(markdown = TRUE)
#> ✔ Writing NAMESPACE.
#> ✔ Setting active project to "<no active project>".R packages satisfy the is_r_package criterion.
A criterion is an object that contains a find_file() function.
With pkg as working directory, the function works like file.path(), rooted at the working directory:
setwd(pkg)
is_r_package
#> Root criterion: contains a file 'DESCRIPTION' with contents matching '^Package: '
is_r_package$find_file()
#> [1] "/tmp/RtmpXXXXXX/demopkg"
is_r_package$find_file("tests", "testthat")
#> [1] "/tmp/RtmpXXXXXX/demopkg/tests/testthat"This works identically when starting from a subdirectory:
setwd(file.path(pkg, "R"))
is_r_package$find_file()
#> [1] "/tmp/RtmpXXXXXX/demopkg"
is_r_package$find_file("tests", "testthat")
#> [1] "/tmp/RtmpXXXXXX/demopkg/tests/testthat"There is one exception: if the first component passed to find_file() is already an absolute path.
This allows safely applying this function to paths that may be absolute or relative:
setwd(file.path(pkg, "R"))
path <- is_r_package$find_file()
is_r_package$find_file(path, "tests", "testthat")
#> [1] "/tmp/RtmpXXXXXX/demopkg/tests/testthat"As long as you are sure that your working directory is somewhere inside your project, you can retrieve the project root.
Install the package from CRAN:
install.package("rprojroot")Or the development version from GitHub with:
# install.packages("pak")
pak::pak("r-lib/rprojroot")See the documentation for more detail.
Please note that the rprojroot project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.