talira

Run R code with temporarily modified global state

open sourceMITfree

withr is an R package of functions that change a piece of global state for the duration of a block of code and restore it afterwards, so side effects don't leak. Each setting has a with_() form that wraps a block and a local_() form that lasts until the calling function exits: the working directory, environment variables, options, the locale, PATH and library paths, the random seed, graphics parameters and devices, temporary and normal files, and file and database connections. Many of the functions began in devtools. It's widely used in package tests, alongside testthat.

Problems it solves

  • change an environment variable or option in a test without leaving it changed afterwards
  • run part of my R code in another working directory and always switch back
  • make sure temporary files and connections get cleaned up when my function exits

Features

  • with_*() functions change a setting for one block of code and restore it
  • local_*() functions keep a change until the calling function exits
  • Working directory, environment variables, options, locale, PATH and library paths
  • Seeds, graphics parameters and graphics devices
  • Temporary files and file or database connections that are cleaned up automatically