In rprojroot, a criterion is an object that contains a find_file() function. This function identifies the project root by looking for a specific file pattern (e.g., an R package root is identified by the presence of a DESCRIPTION file).
When you call criterion$find_file(...), it behaves similarly to file.path(), but it is always rooted at the identified project root rather than the current working directory. This allows you to reliably locate files regardless of where your R session is currently pointed, as long as your working directory is somewhere within the project.
Key behaviors:
- Relative paths: If you pass relative components to
find_file(), they are appended to the project root. - Absolute paths: If the first component passed to
find_file() is an absolute path, the function uses that path as the starting point, allowing for safe path manipulation even when the input path is already absolute.
library(rprojroot)
# Assuming 'is_r_package' is a criterion for R packages
# and 'pkg' is the path to an R package root
# 1. Find the root
root_path <- is_r_package$find_file()
# 2. Find a file relative to that root
# This works even if your working directory is set to a subdirectory of the project
setwd(file.path(pkg, "R"))
target_file <- is_r_package$find_file("tests", "testthat")
# 3. Safely handle absolute paths
# If 'root_path' is absolute, find_file() handles it correctly
path_from_absolute <- is_r_package$find_file(root_path, "tests", "testthat")