Withr - Run Code ‘With’ Modified State

Travis-CI Build Status AppVeyor Build Status Coverage Status CRAN Version

A set of functions to run code ‘with’ safely and temporarily modified global state. There are two sets of functions, those prefixed with with_ and those with local_. The former reset their state as soon as the code argument has been evaluated. The latter reset when they reach the end of their scope, usually at the end of a function body.

Many of these functions were originally a part of the devtools package, this provides a simple package with limited dependencies to provide access to these functions.

There are also with_() and local_() functions to construct new with_* and local_* functions if needed.

dir.create("test")
getwd()
#> [1] "/private/var/folders/dt/r5s12t392tb5sk181j3gs4zw0000gn/T/Rtmp8xR1aN"
with_dir("test", getwd())
#> [1] "/private/var/folders/dt/r5s12t392tb5sk181j3gs4zw0000gn/T/Rtmp8xR1aN/test"
getwd()
#> [1] "/private/var/folders/dt/r5s12t392tb5sk181j3gs4zw0000gn/T/Rtmp8xR1aN"
unlink("test")

Sys.getenv("HADLEY")
#> [1] ""
with_envvar(c("HADLEY" = 2), Sys.getenv("HADLEY"))
#> [1] "2"
Sys.getenv("HADLEY")
#> [1] ""

with_envvar(c("A" = 1),
  with_envvar(c("A" = 2), action = "suffix", Sys.getenv("A"))
)
#> [1] "1 2"

See Also