
A set of functions to run code with safely and temporarily modifiedglobal state, withr makes working with the global state, i.e. sideeffects, less error-prone.
Pure functions, such as thesum() function, are easy tounderstand and reason about: they always map the same input to the sameoutput and have no other impact on the workspace. In other words, purefunctions have noside effects: they are not affected by, nordo they affect, the global state in any way apart from the value theyreturn.
The behavior of some functionsis affected by the globalstate. Consider theread.csv() function: it takes afilename as an input and returns the contents as an output. In thiscase, the output depends on the contents of the file; i.e. the output isaffected by the global state. Functions like this deal with sideeffects.
The purpose of the withr package is to help you manage side effectsin your code. You may want to run code with secret information, such asan API key, that you store as an environment variable. You may also wantto run code with certain options, with a given random-seed, or with aparticular working-directory.
The withr package helps you manage these situations, and more, byproviding functions to modify the global state temporarily, and safely.These functions modify one of the global settings for duration of ablock of code, then automatically reset it after the block iscompleted.
#Install the latest version with:install.packages("withr")Many of these functions were originally a part of thedevtools package, thisprovides a simple package with limited dependencies to provide access tothese functions.
with_collate() /local_collate() -collation orderwith_dir() /local_dir() - workingdirectorywith_envvar() /local_envvar() -environment variableswith_libpaths() /local_libpaths() -library pathswith_locale() /local_locale() - anylocale settingwith_makevars() /local_makevars() /set_makevars() - makevars variableswith_options() /local_options() -optionswith_par() /local_par() - graphicsparameterswith_path() /local_path() - PATHenvironment variablewith_*() andlocal_*() functions for thebuilt in R devices,bmp,cairo_pdf,cairo_ps,pdf,postscript,svg,tiff,xfig,png,jpeg.with_connection() /local_connection() - Rfile connectionswith_db_connection() /local_db_connection() - DB connectionswith_package() /local_package(),with_namespace() /local_namespace() andwith_environment() /local_environment() - torun code with modified object search paths.with_tempfile() /local_tempfile() -create and clean up a temp file.with_file() /local_file() - create andclean up a normal file.with_message_sink() /local_message_sink()- divert messagewith_output_sink() /local_output_sink() -divert outputwith_preserve_seed() /with_seed()-specify seedswith_temp_libpaths() /local_temp_libpaths() - library pathsdefer() /defer_parent() - deferwith_timezone() /local_timezone() -timezoneswith_rng_version() /local_rng_version() -random number generation versionThere are two sets of functions, those prefixed withwith_ and those withlocal_. The former resettheir state as soon as thecode argument has beenevaluated. The latter reset when they reach the end of their scope,usually at the end of a function body.
par("col"="black")my_plot<-function(new) {with_par(list(col ="red",pch =19),plot(mtcars$hp, mtcars$wt) )par("col")}my_plot()
#> [1] "black"par("col")#> [1] "black"f <- function(x) { local_envvar(c("WITHR" = 2)) Sys.getenv("WITHR")}f()#> [1] "2"Sys.getenv("WITHR")#> [1] ""There are alsowith_() andlocal_()functions to construct newwith_* andlocal_*functions if needed.
Sys.getenv("WITHR")#> [1] ""with_envvar(c("WITHR"=2),Sys.getenv("WITHR"))#> [1] "2"Sys.getenv("WITHR")#> [1] ""with_envvar(c("A"=1),with_envvar(c("A"=2),action ="suffix",Sys.getenv("A")))#> [1] "1 2"