Skip to contents

Temporarily change the here() root

Usage

with_here(new_here, expr, chdir = FALSE, verbose = FALSE)

local_here(
  new_here,
  chdir = FALSE,
  verbose = FALSE,
  .local_envir = parent.frame()
)

Arguments

new_here

new temporary here root directory

expr

expression to evaluate

chdir

also temporarily change working directory

verbose

show here's messages on setting new root

.local_envir

the environment to use for scoping, see withr::local_dir()

Value

with_here() returns the result of the expression. local_here() returns the original value of here(), before the change.

Details

Changes here::here() to temporarily point to a new directory. Automatically changes back to the original value when finished.

The with_* and local_* flavours of this functionality mimics that which is typically used in the withr package.

Author

Torbjørn Lindahl

Examples

library(here)
#> here() starts at /home/runner/work/wither/wither
library(withr)

d <- local_tempdir()

cat("here() is initially:", here(), "\n")
#> here() is initially: /home/runner/work/wither/wither 

# temporarily do things uner a different here() root:
with_here(d, cat("but here() is now:", here(), "\n"))
#> Error in with_here(d, cat("but here() is now:", here(), "\n")): new_here must be a directory

# check that everything is shifted back
cat("here() is now again:", here(), "\n")
#> here() is now again: /home/runner/work/wither/wither 

local({

  d <- local_tempdir()

  cat("here was initially: ", here(), "\n")

  local_here(d)

  cat("after local_here(), here() is: ",here(),"\n")
  stopifnot(normalizePath(d) == normalizePath(here()))

  # do something that requires here() be elsewhere

})
#> here was initially:  /home/runner/work/wither/wither 
#> here() starts at /tmp/Rtmp8rziX4/file134119a13caf
#> after local_here(), here() is:  /tmp/Rtmp8rziX4/file134119a13caf 
#> here() starts at /home/runner/work/wither/wither

cat("outside the block, here() is again:", here(), "\n")
#> outside the block, here() is again: /home/runner/work/wither/wither