knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

set.seed(20230702)

clean_output <- function(x, options) {
  # Side effect
  usethis::use_build_ignore("index.md")

  x <- gsub("0x[0-9a-f]+", "0xdeadbeef", x)
  x <- gsub("dataframe_[0-9]*_[0-9]*", "      dataframe_42_42      ", x)
  x <- gsub("[0-9]*\\.___row_number ASC", "42.___row_number ASC", x)

  index <- x
  index <- gsub("─", "-", index)
  index <- strsplit(paste(index, collapse = "\n"), "\n---\n")[[1]][[2]]
  writeLines(index, "index.md")

  x <- fansi::strip_sgr(x)
  x
}

options(cli.num_colors = 256)

local({
  hook_source <- knitr::knit_hooks$get("document")
  knitr::knit_hooks$set(document = clean_output)
})

rlang::local_interactive(FALSE)

rprojroot

Lifecycle: stable rcc CRAN_Status_Badge Codecov test coverage

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)

Example

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.

dir <- tempfile()
pkg <- usethis::create_package(dir)

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
is_r_package$find_file()
is_r_package$find_file("tests", "testthat")

This works identically when starting from a subdirectory:

setwd(file.path(pkg, "R"))
is_r_package$find_file()
is_r_package$find_file("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")

As long as you are sure that your working directory is somewhere inside your project, you can retrieve the project root.

Installation and further reading

Install the package from CRAN:

install.package("rprojroot")

See the documentation for more detail.


Code of Conduct

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.



krlmlr/rprojroot documentation built on June 14, 2025, 3:18 p.m.