A set of functions to run code with safely and temporarily modified global state, withr makes working with the global state, i.e. side effects, less error-prone.
Pure functions, such as the
sum() function, are easy to understand and reason about: they always map the same input to the same output and have no other impact on the workspace. In other words, pure functions have no side effects: they are not affected by, nor do they affect, the global state in any way apart from the value they return.
The behavior of some functions is affected by the global state. Consider the
read.csv() function: it takes a filename as an input and returns the contents as an output. In this case, the output depends on the contents of the file; i.e. the output is affected by the global state. Functions like this deal with side effects.
The purpose of the withr package is to help you manage side effects in your code. You may want to run code with secret information, such as an API key, that you store as an environment variable. You may also want to run code with certain options, with a given random-seed, or with a particular working-directory.
The withr package helps you manage these situations, and more, by providing functions to modify the global state temporarily, and safely. These functions modify one of the global settings for duration of a block of code, then automatically reset it after the block is completed.
#Install the latest version with: install.packages("withr")
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.
local_collate()- collation order
local_dir()- working directory
local_envvar()- environment variables
local_libpaths()- library paths
local_locale()- any locale setting
set_makevars()- makevars variables
local_par()- graphics parameters
local_path()- PATH environment variable
local_*()functions for the built in R devices,
local_connection()- R file connections
local_db_connection()- DB conections
local_tempfile()- create and clean up a temp file.
local_file()- create and clean up a normal file.
local_message_sink()- divert message
local_output_sink()- divert output
with_seed()- specify seeds
local_temp_libpaths()- library paths
local_rng_version()- random number generation version
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.