getwd()
#> [1] "/home/runner/work/withr/withr/docs/reference"
with_dir(tempdir(), getwd())
-#> [1] "/tmp/Rtmp7gdDMb"
+#> [1] "/tmp/RtmpcHnEKr"
getwd()
#> [1] "/home/runner/work/withr/withr/docs/reference"
diff --git a/search.json b/search.json
index 16dcb51..4af1845 100644
--- a/search.json
+++ b/search.json
@@ -1 +1 @@
-[{"path":"https://withr.r-lib.org/LICENSE.html","id":null,"dir":"","previous_headings":"","what":"MIT License","title":"MIT License","text":"Copyright (c) 2020 withr authors Permission hereby granted, free charge, person obtaining copy software associated documentation files (“Software”), deal Software without restriction, including without limitation rights use, copy, modify, merge, publish, distribute, sublicense, /sell copies Software, permit persons Software furnished , subject following conditions: copyright notice permission notice shall included copies substantial portions Software. SOFTWARE PROVIDED “”, WITHOUT WARRANTY KIND, EXPRESS IMPLIED, INCLUDING LIMITED WARRANTIES MERCHANTABILITY, FITNESS PARTICULAR PURPOSE NONINFRINGEMENT. EVENT SHALL AUTHORS COPYRIGHT HOLDERS LIABLE CLAIM, DAMAGES LIABILITY, WHETHER ACTION CONTRACT, TORT OTHERWISE, ARISING , CONNECTION SOFTWARE USE DEALINGS SOFTWARE.","code":""},{"path":"https://withr.r-lib.org/MAINTENANCE.html","id":"current-state","dir":"","previous_headings":"","what":"Current state","title":"NA","text":"withr generally works use cases doesn’t need great deal reoccurring maintenance.","code":""},{"path":"https://withr.r-lib.org/MAINTENANCE.html","id":"future-directions","dir":"","previous_headings":"","what":"Future directions","title":"NA","text":"Harmonize implementation similar functinos rlang, already somewhat now compat-defer implementation.","code":""},{"path":"https://withr.r-lib.org/articles/withr.html","id":"its-dangerous-to-change-state","dir":"Articles","previous_headings":"","what":"It’s dangerous to change state","title":"Changing and restoring state","text":"Whenever possible, desirable write -called pure functions. property focus function change surrounding R landscape, .e. change things like search path, global options, working directory. behaviour functions differs running function, ’ve modified landscape. Changing landscape bad makes code much harder understand. ’s sloppy() function prints number specific number significant digits, adjusting R’s global “digits” option. Notice pi prints differently call sloppy()? Calling sloppy() side effect: changes “digits” option globally, just within scope operations. want avoid. Don’t worry, ’re restoring global state (specifically, “digits” option) behind scenes . Sometimes avoid modifying state world, case just make sure put things back way found . withr package .","code":"sloppy <- function(x, sig_digits) { options(digits = sig_digits) print(x) } pi #> [1] 3.141593 sloppy(pi, 2) #> [1] 3.1 pi #> [1] 3.1"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"the-base-solution-on-exit","dir":"Articles","previous_headings":"","what":"The base solution: on.exit()","title":"Changing and restoring state","text":"first function know base R’s .exit(). Inside function body, every time something undone exit, immediately register cleanup code .exit(expr, add = TRUE)1. neat() improvement sloppy(), uses .exit() ensure “digits” option restored original value. .exit() also works exit function abnormally, .e. due error. official tools, like .exit(), better choice --solution problem. .exit() useful function, ’s flexible. withr package provides extensible .exit()-inspired toolkit.","code":"neat <- function(x, sig_digits) { op <- options(digits = sig_digits) on.exit(options(op), add = TRUE) print(x) } pi #> [1] 3.141593 neat(pi, 2) #> [1] 3.1 pi #> [1] 3.141593"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"defer-is-the-foundation-of-withr","dir":"Articles","previous_headings":"","what":"defer() is the foundation of withr","title":"Changing and restoring state","text":"defer() core function withr much like .exit(), .e. schedules execution arbitrary code current function exits: withr::defer() basically drop-substitute .exit(), three key differences explore : Different default behaviour around effect series two calls Control environment deferred events associated Ability work global environment focus using withr inside functions. See blog post Self-cleaning test fixtures testthat vignette Test fixtures use withr inside tests.","code":"neater <- function(x, sig_digits) { op <- options(digits = sig_digits) defer(options(op)) print(x) } pi #> [1] 3.141593 neater(pi, 2) #> [1] 3.1 pi #> [1] 3.141593"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"last-in-first-out","dir":"Articles","previous_headings":"","what":"Last-in, first-out","title":"Changing and restoring state","text":"make one call defer(), default, adds expressions top stack deferred actions. contrast, default, subsequent call .exit() overwrites deferred actions registered previous call. Oops, still socks ! last-, first-, stack-like behaviour defer() tends want applications. get behaviour .exit(), remember call add = TRUE, = FALSE2. Conversely, want defer() first-, first-behaviour, specify priority = \"last\".","code":"defer_stack <- function() { cat(\"put on socks\\n\") defer(cat(\"take off socks\\n\")) cat(\"put on shoes\\n\") defer(cat(\"take off shoes\\n\")) } defer_stack() #> put on socks #> put on shoes #> take off shoes #> take off socks on_exit_last_one_wins <- function() { cat(\"put on socks\\n\") on.exit(cat(\"take off socks\\n\")) cat(\"put on shoes\\n\") on.exit(cat(\"take off shoes\\n\")) } on_exit_last_one_wins() #> put on socks #> put on shoes #> take off shoes on_exit_stack <- function() { cat(\"put on socks\\n\") on.exit(cat(\"take off socks\\n\"), add = TRUE, after = FALSE) cat(\"put on shoes\\n\") on.exit(cat(\"take off shoes\\n\"), add = TRUE, after = FALSE) } on_exit_stack() #> put on socks #> put on shoes #> take off shoes #> take off socks defer_queue <- function() { cat(\"Adam gets in line for ice cream\\n\") defer(cat(\"Adam gets ice cream\\n\"), priority = \"last\") cat(\"Beth gets in line for ice cream\\n\") defer(cat(\"Beth gets ice cream\\n\"), priority = \"last\") } defer_queue() #> Adam gets in line for ice cream #> Beth gets in line for ice cream #> Adam gets ice cream #> Beth gets ice cream"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"local-functions-and-with-functions","dir":"Articles","previous_headings":"","what":"“Local” functions (and “with” functions)","title":"Changing and restoring state","text":".exit() withr::defer() schedule actions executed certain environment goes scope, typically execution environment function. envir argument withr::defer() lets specify different environment, makes possible create customised .exit() extensions. Let’s look neater() function . first two lines typical .exit() maneuvers , order, record original state, arrange eventual restoration, change . real life, can much involved might want wrap logic helper function. can’t wrap .exit() way, ’s way reach back correct parent frame schedule cleanup . defer(), can! custom helper, called local_digits(). can use local_digits() keep manipulation digits local function. can even call local_digits() multiple times inside function. call local_digits() effect next function exits, ever comes first. Certain state changes, modifying global options, come often withr offers pre-made helpers. helpers come two forms: local_*() functions, like one just made, with_*() functions, explain . state change helpers withr likely find useful: didn’t really need write local_digits() helper, built-withr::local_options() also gets job done: local_*() functions target slightly different use case with_*() functions, inspired base R’s () function: with_*() functions best executing small snippet code modified state local_*() functions best modifying state “now function exits” ’s best minimize footprint state modifications. Therefore, use with_*() functions can. forces put lots (indented) code inside with_*(), e.g. function’s body, ’s better use local_*().","code":"neater <- function(x, sig_digits) { op <- options(digits = sig_digits) # record orig. \"digits\" & change \"digits\" defer(options(op)) # schedule restoration of \"digits\" print(x) } local_digits <- function(sig_digits, envir = parent.frame()) { op <- options(digits = sig_digits) defer(options(op), envir = envir) } neato <- function(x, digits) { local_digits(digits) print(x) } pi #> [1] 3.141593 neato(pi, 2) #> [1] 3.1 neato(pi, 4) #> [1] 3.142 neatful <- function(x) { local_digits(1) print(x) local_digits(3) print(x) local_digits(5) print(x) } neatful(pi) #> [1] 3 #> [1] 3.14 #> [1] 3.1416 neatest <- function(x, sig_digits) { local_options(list(digits = sig_digits)) print(x) } pi #> [1] 3.141593 neatest(pi, 2) #> [1] 3.1 neatest(pi, 4) #> [1] 3.142 neat_with <- function(x, sig_digits) { # imagine lots of code here withr::with_options( list(digits = sig_digits), print(x) ) # ... and a lot more code here } neat_local <- function(x, sig_digits) { withr::local_options(list(digits = sig_digits)) print(x) # imagine lots of code here }"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"deferring-events-on-the-global-environment","dir":"Articles","previous_headings":"","what":"Deferring events on the global environment","title":"Changing and restoring state","text":"one last difference withr::defer() .exit(): ability defer events global environment3. first, sounds pretty weird propose scheduling deferred actions global environment. ’s ephemeral, way function execution environments . goes scope rarely, .e. exit R. want ? answer : development purposes. developing functions tests use withr, ’s useful able execute code interactively, without error, ability trigger deferred events. ’s hard develop functions work one way inside function, another way global environment (, worse, throw error). ’s defer() (functions based ) works interactive session. Note example running vignette, doesn’t look exactly ’ll see interactively. defer events global environment first time, get message alerts situation: add subsequent events, message repeated. Since global environment isn’t perishable, like test environment , call deferred_run() explicitly execute deferred events. can also clear , without running, deferred_clear().","code":"library(withr) defer(print(\"hi\")) pi #> [1] 3.141593 # this adds another deferred event, but does not re-message local_digits(3) pi #> [1] 3.14 deferred_run() #> [1] \"hi\" #> Ran 2/2 deferred expressions pi #> [1] 3.141593 defer(print(\"hi\")) #> Setting global deferred event(s). #> i These will be run: #> * Automatically, when the R session ends. #> * On demand, if you call `withr::deferred_run()`. #> i Use `withr::deferred_clear()` to clear them without executing."},{"path":"https://withr.r-lib.org/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Jim Hester. Author. Lionel Henry. Author, maintainer. Kirill Müller. Author. Kevin Ushey. Author. Hadley Wickham. Author. Winston Chang. Author. Jennifer Bryan. Contributor. Richard Cotton. Contributor. . Copyright holder, funder.","code":""},{"path":"https://withr.r-lib.org/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"Hester J, Henry L, Müller K, Ushey K, Wickham H, Chang W (2024). withr: Run Code '' Temporarily Modified Global State. R package version 3.0.2, https://github.com/r-lib/withr#readme, https://withr.r-lib.org.","code":"@Manual{, title = {withr: Run Code 'With' Temporarily Modified Global State}, author = {Jim Hester and Lionel Henry and Kirill Müller and Kevin Ushey and Hadley Wickham and Winston Chang}, year = {2024}, note = {R package version 3.0.2, https://github.com/r-lib/withr#readme}, url = {https://withr.r-lib.org}, }"},{"path":[]},{"path":"https://withr.r-lib.org/index.html","id":"overview","dir":"","previous_headings":"","what":"Overview","title":"Run Code With Temporarily Modified Global State","text":"set functions run code safely temporarily modified global state, withr makes working global state, .e. side effects, less error-prone. Pure functions, sum() function, easy understand reason : always map input output impact workspace. words, pure functions side effects: affected , affect, global state way apart value return. behavior functions affected global state. Consider read.csv() function: takes filename input returns contents output. case, output depends contents file; .e. output affected global state. Functions like deal side effects. purpose withr package help manage side effects code. may want run code secret information, API key, store environment variable. may also want run code certain options, given random-seed, particular working-directory. withr package helps manage situations, , providing functions modify global state temporarily, safely. functions modify one global settings duration block code, automatically reset block completed.","code":""},{"path":"https://withr.r-lib.org/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Run Code With Temporarily Modified Global State","text":"Many functions originally part devtools package, provides simple package limited dependencies provide access functions. with_collate() / local_collate() - collation order with_dir() / local_dir() - working directory with_envvar() / local_envvar() - environment variables with_libpaths() / local_libpaths() - library paths with_locale() / local_locale() - locale setting with_makevars() / local_makevars() / set_makevars() - makevars variables with_options() / local_options() - options with_par() / local_par() - graphics parameters with_path() / local_path() - PATH environment variable with_*() local_*() functions built R devices, bmp, cairo_pdf, cairo_ps, pdf, postscript, svg, tiff, xfig, png, jpeg. with_connection() / local_connection() - R file connections with_db_connection() / local_db_connection() - DB connections with_package() / local_package(), with_namespace() / local_namespace() with_environment() / local_environment() - run code modified object search paths. with_tempfile() / local_tempfile() - create clean temp file. with_file() / local_file() - create clean normal file. with_message_sink() / local_message_sink() - divert message with_output_sink() / local_output_sink() - divert output with_preserve_seed() / with_seed()- specify seeds with_temp_libpaths() / local_temp_libpaths() - library paths defer() / defer_parent() - defer with_timezone() / local_timezone() - timezones with_rng_version() / local_rng_version() - random number generation version","code":"#Install the latest version with: install.packages(\"withr\")"},{"path":"https://withr.r-lib.org/index.html","id":"usage","dir":"","previous_headings":"","what":"Usage","title":"Run Code With Temporarily Modified Global State","text":"two sets functions, prefixed with_ local_. former reset state soon code argument evaluated. latter reset reach end scope, usually end function body. also with_() local_() functions construct new with_* local_* functions needed.","code":"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] \"\" 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\""},{"path":"https://withr.r-lib.org/index.html","id":"see-also","dir":"","previous_headings":"","what":"See Also","title":"Run Code With Temporarily Modified Global State","text":"Devtools","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":null,"dir":"Reference","previous_headings":"","what":"Defer Evaluation of an Expression — defer","title":"Defer Evaluation of an Expression — defer","text":"Similar .exit(), allows one attach expression evaluated exiting frame currently stack. provides nice mechanism scoping side effects duration function's execution.","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Defer Evaluation of an Expression — defer","text":"","code":"defer(expr, envir = parent.frame(), priority = c(\"first\", \"last\")) defer_parent(expr, priority = c(\"first\", \"last\")) deferred_run(envir = parent.frame()) deferred_clear(envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/defer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Defer Evaluation of an Expression — defer","text":"expr [expression] expression evaluated. envir [environment] Attach exit handlers environment. Typically, either current environment parent frame (accessed parent.frame()). priority [character(1)] Specify whether handler executed \"first\" \"last\", relative registered handlers environment.","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Defer Evaluation of an Expression — defer","text":"defer() works attaching handlers requested environment (attribute called \"handlers\"), registering exit handler executes registered handler function associated requested environment finishes execution. Deferred events can set global environment, primarily facilitate interactive development code intended executed inside function test. message alerts user fact explicit deferred_run() way trigger deferred events. Use deferred_clear() clear without evaluation. global environment scenario main motivation functions.","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":"running-handlers-within-source-","dir":"Reference","previous_headings":"","what":"Running handlers within source()","title":"Defer Evaluation of an Expression — defer","text":"withr handlers run within source() run source() exits rather line line. case script sourced globalenv(). local environment, caller needs set options(withr.hook_source = TRUE). avoid paying penalty detecting source() normal usage defer().","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Defer Evaluation of an Expression — defer","text":"","code":"# define a 'local' function that creates a file, and # removes it when the parent function has finished executing local_file <- function(path) { file.create(path) defer_parent(unlink(path)) } # create tempfile path path <- tempfile() # use 'local_file' in a function local({ local_file(path) stopifnot(file.exists(path)) }) # file is deleted as we leave 'local' local stopifnot(!file.exists(path)) # investigate how 'defer' modifies the # executing function's environment local({ local_file(path) print(attributes(environment())) }) #> NULL # Note that examples lack function scoping so deferred calls are # generally executed immediately defer(print(\"one\")) #> [1] \"one\" defer(print(\"two\")) #> [1] \"two\""},{"path":"https://withr.r-lib.org/reference/devices.html","id":null,"dir":"Reference","previous_headings":"","what":"Graphics devices — devices","title":"Graphics devices — devices","text":"Temporarily use graphics device.","code":""},{"path":"https://withr.r-lib.org/reference/devices.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Graphics devices — devices","text":"","code":"with_bmp(new, code, ...) local_bmp(new, ..., .local_envir = parent.frame()) with_cairo_pdf(new, code, ...) local_cairo_pdf(new, ..., .local_envir = parent.frame()) with_cairo_ps(new, code, ...) local_cairo_ps(new, ..., .local_envir = parent.frame()) with_pdf(new, code, ...) local_pdf(new, ..., .local_envir = parent.frame()) with_postscript(new, code, ...) local_postscript(new, ..., .local_envir = parent.frame()) with_svg(new, code, ...) local_svg(new, ..., .local_envir = parent.frame()) with_tiff(new, code, ...) local_tiff(new, ..., .local_envir = parent.frame()) with_xfig(new, code, ...) local_xfig(new, ..., .local_envir = parent.frame()) with_png(new, code, ...) local_png(new, ..., .local_envir = parent.frame()) with_jpeg(new, code, ...) local_jpeg(new, ..., .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/devices.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Graphics devices — devices","text":"new [named character] New graphics device code [] Code execute temporary environment ... Additional arguments passed graphics device. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/devices.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Graphics devices — devices","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/devices.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Graphics devices — devices","text":"with_bmp() local_bmp() wrap around grDevices::bmp(). with_cairo_pdf() local_cairo_pdf() wrap around grDevices::cairo_pdf(). with_cairo_ps() local_cairo_ps() wrap around grDevices::cairo_ps(). with_pdf() local_pdf() wrap around grDevices::pdf(). with_postscript() local_postscript() wrap around grDevices::postscript(). with_svg() local_svg() wrap around grDevices::svg(). with_tiff() local_tiff() wrap around grDevices::tiff(). with_xfig() local_xfig() wrap around grDevices::xfig(). with_png() local_png() wrap around grDevices::png(). with_jpeg() local_jpeg() wrap around grDevices::jpeg().","code":""},{"path":"https://withr.r-lib.org/reference/devices.html","id":"functions","dir":"Reference","previous_headings":"","what":"Functions","title":"Graphics devices — devices","text":"with_bmp(): BMP device with_cairo_pdf(): CAIRO_PDF device with_cairo_ps(): CAIRO_PS device with_pdf(): PDF device with_postscript(): POSTSCRIPT device with_svg(): SVG device with_tiff(): TIFF device with_xfig(): XFIG device with_png(): PNG device with_jpeg(): JPEG device","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/devices.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Graphics devices — devices","text":"","code":"# dimensions are in inches with_pdf(file.path(tempdir(), \"test.pdf\"), width = 7, height = 5, plot(runif(5)) ) # dimensions are in pixels with_png(file.path(tempdir(), \"test.png\"), width = 800, height = 600, plot(runif(5)) )"},{"path":"https://withr.r-lib.org/reference/global_defer.html","id":null,"dir":"Reference","previous_headings":"","what":"Defer expression globally — global_defer","title":"Defer expression globally — global_defer","text":"function mostly internal. exported called standalone defer() implementations defer expressions global environment.","code":""},{"path":"https://withr.r-lib.org/reference/global_defer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Defer expression globally — global_defer","text":"","code":"global_defer(expr, priority = c(\"first\", \"last\"))"},{"path":"https://withr.r-lib.org/reference/global_defer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Defer expression globally — global_defer","text":"expr [expression] expression evaluated. priority [character(1)] Specify whether handler executed \"first\" \"last\", relative registered handlers environment.","code":""},{"path":"https://withr.r-lib.org/reference/makevars_user.html","id":null,"dir":"Reference","previous_headings":"","what":"Shim for tools::makevars_user() — makevars_user","title":"Shim for tools::makevars_user() — makevars_user","text":"Shim tools::makevars_user()","code":""},{"path":"https://withr.r-lib.org/reference/makevars_user.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Shim for tools::makevars_user() — makevars_user","text":"","code":"makevars_user()"},{"path":"https://withr.r-lib.org/reference/set_makevars.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new Makevars file, by adding new variables — set_makevars","title":"Create a new Makevars file, by adding new variables — set_makevars","text":"probably want with_makevars() instead function.","code":""},{"path":"https://withr.r-lib.org/reference/set_makevars.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new Makevars file, by adding new variables — set_makevars","text":"","code":"set_makevars( variables, old_path = makevars_user(), new_path = tempfile(), assignment = c(\"=\", \":=\", \"?=\", \"+=\") )"},{"path":"https://withr.r-lib.org/reference/set_makevars.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new Makevars file, by adding new variables — set_makevars","text":"variables [named character] new variables values old_path [character(1)] location existing Makevars file modify. new_path [character(1)] location new Makevars file assignment [character(1)] assignment type use.","code":""},{"path":"https://withr.r-lib.org/reference/set_makevars.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a new Makevars file, by adding new variables — set_makevars","text":"Unlike with_makevars(), activate new Makevars file, .e. set R_MAKEVARS_USER environment variable.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new ","title":"Create a new ","text":"constructors with_... local_... functions. needed want alter global state covered existing with_... functions, see withr overview.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new ","text":"","code":"local_( set, reset = set, get = NULL, ..., envir = parent.frame(), new = TRUE, dots = FALSE ) with_(set, reset = set, get = NULL, ..., envir = parent.frame(), new = TRUE)"},{"path":"https://withr.r-lib.org/reference/with_.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new ","text":"set [function(...)] Function used set state. return value function old state, passed back reset() function clean state. function can arbitrarily many arguments, replicated formals returned function. reset [function(x)] Function used reset state. first argument can named arbitrarily, arguments default values, \"dots\" argument, supported used: function called reset(old). get [function(...)] Optionally, getter function. supplied, .exit() restoration set calling set. robust edge cases. technical reasons, getter function must interface set, means passed new values well. can safely ignored. ... dots future extensions must empty. envir [environment] Environment returned function. new [logical(1)] Replace first argument set function new? Set FALSE set function optional arguments.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Create a new ","text":"[function(new, code, ...)] function least two arguments, new: New state use code: Code run state. arguments function passed set added returned function. set arguments, new FALSE, returned function code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a new ","text":"with_... functions reset state immediately code argument evaluated. local_... functions reset arguments go scope, usually end function body.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a new ","text":"","code":"with_(setwd) #> function (new, code) #> { #> old <- setwd(dir = new) #> on.exit(setwd(old)) #> force(code) #> } #> global_stack <- list() set_global_state <- function(state, msg = \"Changing global state.\") { global_stack <- c(list(state), global_stack) message(msg) state } reset_global_state <- function(state) { old_state <- global_stack[[1]] global_stack <- global_stack[-1] stopifnot(identical(state, old_state)) } with_(set_global_state, reset_global_state) #> function (new, code, msg = \"Changing global state.\") #> { #> old <- set_global_state(state = new, msg = msg) #> on.exit(reset_global_state(old)) #> force(code) #> } #> "},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":null,"dir":"Reference","previous_headings":"","what":"Collation Order — with_collate","title":"Collation Order — with_collate","text":"Temporarily change collation order changing value LC_COLLATE locale.","code":""},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Collation Order — with_collate","text":"","code":"with_collate(new, code) local_collate(new = list(), .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Collation Order — with_collate","text":"new [character(1)] New collation order code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Collation Order — with_collate","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":"examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Collation Order — with_collate","text":"","code":"# Modify collation order: x <- c(\"bernard\", \"bérénice\", \"béatrice\", \"boris\") with_collate(\"fr_FR\", sort(x)) #> [1] \"béatrice\" \"bérénice\" \"bernard\" \"boris\" with_collate(\"C\", sort(x)) #> [1] \"bernard\" \"boris\" \"béatrice\" \"bérénice\""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":null,"dir":"Reference","previous_headings":"","what":"Connections which close themselves — with_connection","title":"Connections which close themselves — with_connection","text":"R file connections automatically closed.","code":""},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Connections which close themselves — with_connection","text":"","code":"with_connection(con, code) local_connection(con, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Connections which close themselves — with_connection","text":"con with_connection() named list connection(s) create. local_connection() code create single connection, returned. code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Connections which close themselves — with_connection","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Connections which close themselves — with_connection","text":"","code":"with_connection(list(con = file(\"foo\", \"w\")), { writeLines(c(\"foo\", \"bar\"), con) }) read_foo <- function() { readLines(local_connection(file(\"foo\", \"r\"))) } read_foo() #> [1] \"foo\" \"bar\" unlink(\"foo\")"},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":null,"dir":"Reference","previous_headings":"","what":"DBMS Connections which disconnect themselves. — with_db_connection","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"Connections Database Management Systems automatically disconnect. particular connections created DBI::dbConnect() closed DBI::dbDisconnect().","code":""},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"","code":"with_db_connection(con, code) local_db_connection(con, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"con with_db_connection() named list connection(s) create. local_db_connection() code create single connection, returned. code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"","code":"db <- tempfile() with_db_connection( list(con = DBI::dbConnect(RSQLite::SQLite(), db)), { DBI::dbWriteTable(con, \"mtcars\", mtcars) }) head_db_table <- function(...) { con <- local_db_connection(DBI::dbConnect(RSQLite::SQLite(), db)) head(DBI::dbReadTable(con, \"mtcars\"), ...) } head_db_table() #> mpg cyl disp hp drat wt qsec vs am gear carb #> 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 #> 2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 #> 3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 #> 4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 #> 5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 #> 6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 unlink(db)"},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":null,"dir":"Reference","previous_headings":"","what":"Working directory — with_dir","title":"Working directory — with_dir","text":"Temporarily change current working directory.","code":""},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Working directory — with_dir","text":"","code":"with_dir(new, code) local_dir(new = list(), .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Working directory — with_dir","text":"new [character(1)] New working directory code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Working directory — with_dir","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Working directory — with_dir","text":"","code":"getwd() #> [1] \"/home/runner/work/withr/withr/docs/reference\" with_dir(tempdir(), getwd()) #> [1] \"/tmp/Rtmp7gdDMb\""},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":null,"dir":"Reference","previous_headings":"","what":"Environment variables — with_envvar","title":"Environment variables — with_envvar","text":"Temporarily change system environment variables.","code":""},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Environment variables — with_envvar","text":"","code":"with_envvar(new, code, action = \"replace\") local_envvar( .new = list(), ..., action = \"replace\", .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Environment variables — with_envvar","text":"new, .new [named character] New environment variables code [] Code execute temporary environment action new values \"replace\", \"prefix\" \"suffix\" existing variables name. ... Named arguments new environment variables. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Environment variables — with_envvar","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Environment variables — with_envvar","text":"NA used environment variables unset. duplicated variable names last one used.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Environment variables — with_envvar","text":"","code":"with_envvar(new = c(\"GITHUB_PAT\" = \"abcdef\"), Sys.getenv(\"GITHUB_PAT\")) #> [1] \"abcdef\" # with_envvar unsets variables after usage Sys.getenv(\"TEMP_SECRET\") #> [1] \"\" with_envvar(new = c(\"TEMP_SECRET\" = \"secret\"), Sys.getenv(\"TEMP_SECRET\")) #> [1] \"secret\" Sys.getenv(\"TEMP_SECRET\") #> [1] \"\""},{"path":"https://withr.r-lib.org/reference/with_file.html","id":null,"dir":"Reference","previous_headings":"","what":"Files which delete themselves — with_file","title":"Files which delete themselves — with_file","text":"Create files, automatically removed afterwards.","code":""},{"path":"https://withr.r-lib.org/reference/with_file.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Files which delete themselves — with_file","text":"","code":"with_file(file, code) local_file(.file, ..., .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_file.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Files which delete themselves — with_file","text":"file, .file [named list] Files create. code [] Code execute temporary environment ... Additional (possibly named) arguments files create. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_file.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Files which delete themselves — with_file","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_file.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Files which delete themselves — with_file","text":"","code":"with_file(\"file1\", { writeLines(\"foo\", \"file1\") readLines(\"file1\") }) with_file(list(\"file1\" = writeLines(\"foo\", \"file1\")), { readLines(\"file1\") })"},{"path":"https://withr.r-lib.org/reference/with_gctorture2.html","id":null,"dir":"Reference","previous_headings":"","what":"Torture Garbage Collector — with_gctorture2","title":"Torture Garbage Collector — with_gctorture2","text":"Temporarily turn gctorture2 .","code":""},{"path":"https://withr.r-lib.org/reference/with_gctorture2.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Torture Garbage Collector — with_gctorture2","text":"","code":"with_gctorture2(new, code, wait = new, inhibit_release = FALSE)"},{"path":"https://withr.r-lib.org/reference/with_gctorture2.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Torture Garbage Collector — with_gctorture2","text":"new [integer] run GC every 'step' allocations. code [] Code execute temporary environment wait integer; number allocations wait starting GC torture. inhibit_release logical; release free objects re-use: use caution.","code":""},{"path":"https://withr.r-lib.org/reference/with_gctorture2.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Torture Garbage Collector — with_gctorture2","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_language.html","id":null,"dir":"Reference","previous_headings":"","what":"Language — with_language","title":"Language — with_language","text":"Temporarily change language used translations.","code":""},{"path":"https://withr.r-lib.org/reference/with_language.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Language — with_language","text":"","code":"with_language(lang, code) local_language(lang, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_language.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Language — with_language","text":"lang BCP47 language code like \"en\" (English), \"fr\" (French), \"fr_CA\" (French Canadian). Formally, lower case two letter ISO 639 country code, optionally followed \"_\" \"-\" upper case two letter ISO 3166 region code. code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_language.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Language — with_language","text":"","code":"with_language(\"en\", try(mean[[1]])) #> Error in mean[[1]] : object of type 'closure' is not subsettable with_language(\"fr\", try(mean[[1]])) #> Error in mean[[1]] : objet de type 'closure' non indiçable with_language(\"es\", try(mean[[1]])) #> Error in mean[[1]] : objeto de tipo 'closure' no es subconjunto"},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":null,"dir":"Reference","previous_headings":"","what":"Library paths — with_libpaths","title":"Library paths — with_libpaths","text":"Temporarily change library paths.","code":""},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Library paths — with_libpaths","text":"","code":"with_libpaths(new, code, action = \"replace\") local_libpaths(new = list(), action = \"replace\", .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Library paths — with_libpaths","text":"new [character] New library paths code [] Code execute temporary environment action [character(1)] new values \"replace\", \"prefix\" \"suffix\" existing paths. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Library paths — with_libpaths","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Library paths — with_libpaths","text":"","code":".libPaths() #> [1] \"/home/runner/work/_temp/Library\" \"/opt/R/4.4.1/lib/R/site-library\" #> [3] \"/opt/R/4.4.1/lib/R/library\" new_lib <- tempfile() dir.create(new_lib) with_libpaths(new_lib, print(.libPaths())) #> [1] \"/tmp/Rtmp7gdDMb/file16ae650189c3\" \"/opt/R/4.4.1/lib/R/site-library\" #> [3] \"/opt/R/4.4.1/lib/R/library\" unlink(new_lib, recursive = TRUE)"},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":null,"dir":"Reference","previous_headings":"","what":"Locale settings — with_locale","title":"Locale settings — with_locale","text":"Temporarily change locale settings.","code":""},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Locale settings — with_locale","text":"","code":"with_locale(new, code) local_locale(.new = list(), ..., .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Locale settings — with_locale","text":"new, .new [named character] New locale settings code [] Code execute temporary environment ... Additional arguments locale settings. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Locale settings — with_locale","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Locale settings — with_locale","text":"Setting LC_ALL category currently implemented.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Locale settings — with_locale","text":"","code":"## Change locale for time: df <- data.frame( stringsAsFactors = FALSE, date = as.Date(c(\"2019-01-01\", \"2019-02-01\")), value = c(1, 2) ) with_locale(new = c(\"LC_TIME\" = \"es_ES\"), code = plot(df$date, df$value)) #> Warning: OS reports request to set locale to \"es_ES\" cannot be honored ## Compare with: # plot(df$date, df$value) ## Month names: with_locale(new = c(\"LC_TIME\" = \"en_GB\"), format(ISOdate(2000, 1:12, 1), \"%B\")) #> Warning: OS reports request to set locale to \"en_GB\" cannot be honored #> [1] \"January\" \"February\" \"March\" \"April\" \"May\" #> [6] \"June\" \"July\" \"August\" \"September\" \"October\" #> [11] \"November\" \"December\" with_locale(new = c(\"LC_TIME\" = \"es_ES\"), format(ISOdate(2000, 1:12, 1), \"%B\")) #> Warning: OS reports request to set locale to \"es_ES\" cannot be honored #> [1] \"January\" \"February\" \"March\" \"April\" \"May\" #> [6] \"June\" \"July\" \"August\" \"September\" \"October\" #> [11] \"November\" \"December\" ## Change locale for currencies: with_locale(new = c(\"LC_MONETARY\" = \"it_IT\"), Sys.localeconv()) #> Warning: OS reports request to set locale to \"it_IT\" cannot be honored #> decimal_point thousands_sep grouping int_curr_symbol #> \".\" \"\" \"\" \"\" #> currency_symbol mon_decimal_point mon_thousands_sep mon_grouping #> \"\" \"\" \"\" \"\" #> positive_sign negative_sign int_frac_digits frac_digits #> \"\" \"\" \"127\" \"127\" #> p_cs_precedes p_sep_by_space n_cs_precedes n_sep_by_space #> \"127\" \"127\" \"127\" \"127\" #> p_sign_posn n_sign_posn #> \"127\" \"127\" with_locale(new = c(\"LC_MONETARY\" = \"en_US\"), Sys.localeconv()) #> Warning: OS reports request to set locale to \"en_US\" cannot be honored #> decimal_point thousands_sep grouping int_curr_symbol #> \".\" \"\" \"\" \"\" #> currency_symbol mon_decimal_point mon_thousands_sep mon_grouping #> \"\" \"\" \"\" \"\" #> positive_sign negative_sign int_frac_digits frac_digits #> \"\" \"\" \"127\" \"127\" #> p_cs_precedes p_sep_by_space n_cs_precedes n_sep_by_space #> \"127\" \"127\" \"127\" \"127\" #> p_sign_posn n_sign_posn #> \"127\" \"127\" ## Ordering: x <- c(\"bernard\", \"bérénice\", \"béatrice\", \"boris\") with_locale(c(LC_COLLATE = \"fr_FR\"), sort(x)) #> Warning: OS reports request to set locale to \"fr_FR\" cannot be honored #> [1] \"bernard\" \"boris\" \"béatrice\" \"bérénice\" with_locale(c(LC_COLLATE = \"C\"), sort(x)) #> [1] \"bernard\" \"boris\" \"béatrice\" \"bérénice\""},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":null,"dir":"Reference","previous_headings":"","what":"Makevars variables — with_makevars","title":"Makevars variables — with_makevars","text":"Temporarily change contents existing Makevars file.","code":""},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Makevars variables — with_makevars","text":"","code":"with_makevars( new, code, path = makevars_user(), assignment = c(\"=\", \":=\", \"?=\", \"+=\") ) local_makevars( .new = list(), ..., .path = makevars_user(), .assignment = c(\"=\", \":=\", \"?=\", \"+=\"), .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Makevars variables — with_makevars","text":"new, .new [named character] New variables values code [] Code execute temporary environment path, .path [character(1)] location existing Makevars file modify. assignment, .assignment [character(1)] assignment type use. ... Additional new variables values. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Makevars variables — with_makevars","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Makevars variables — with_makevars","text":"Makevars file exists fields new exist existing Makevars file fields added new file. Existing fields included new appended unchanged. Fields exist Makevars new modified use value new.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Makevars variables — with_makevars","text":"","code":"writeLines(\"void foo(int* bar) { *bar = 1; }\\n\", \"foo.c\") system(\"R CMD SHLIB --preclean -c foo.c\") with_makevars(c(CFLAGS = \"-O3\"), system(\"R CMD SHLIB --preclean -c foo.c\")) unlink(c(\"foo.c\", \"foo.so\"))"},{"path":"https://withr.r-lib.org/reference/with_options.html","id":null,"dir":"Reference","previous_headings":"","what":"Options — with_options","title":"Options — with_options","text":"Temporarily change global options.","code":""},{"path":"https://withr.r-lib.org/reference/with_options.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Options — with_options","text":"","code":"with_options(new, code) local_options(.new = list(), ..., .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_options.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Options — with_options","text":"new, .new [named list] New options values code [] Code execute temporary environment ... Additional options values .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_options.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Options — with_options","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_options.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Options — with_options","text":"","code":"# number of significant digits to print getOption(\"digits\") #> [1] 7 # modify temporarily the number of significant digits to print with_options(list(digits = 3), getOption(\"digits\")) #> [1] 3 with_options(list(digits = 3), print(pi)) #> [1] 3.14 # modify temporarily the character to be used as the decimal point getOption(\"digits\") #> [1] 7 with_options(list(OutDec = \",\"), print(pi)) #> [1] 3,141593 # modify temporarily multiple options with_options(list(OutDec = \",\", digits = 3), print(pi)) #> [1] 3,14 # modify, within the scope of the function, the number of # significant digits to print print_3_digits <- function(x) { # assign 3 to the option \"digits\" for the rest of this function # after the function exits, the option will return to its previous # value local_options(list(digits = 3)) print(x) } print_3_digits(pi) # returns 3.14 #> [1] 3.14 print(pi) # returns 3.141593 #> [1] 3.141593"},{"path":"https://withr.r-lib.org/reference/with_package.html","id":null,"dir":"Reference","previous_headings":"","what":"Execute code with a modified search path — with_package","title":"Execute code with a modified search path — with_package","text":"with_package() attaches package search path, executes code, removes package search path. package namespace unloaded however. with_namespace() thing, attaches package namespace search path, objects (even unexported ones) also available search path.","code":""},{"path":"https://withr.r-lib.org/reference/with_package.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Execute code with a modified search path — with_package","text":"","code":"with_package( package, code, pos = 2, lib.loc = NULL, character.only = TRUE, logical.return = FALSE, warn.conflicts = FALSE, quietly = TRUE, verbose = getOption(\"verbose\") ) local_package( package, pos = 2, lib.loc = NULL, character.only = TRUE, logical.return = FALSE, warn.conflicts = FALSE, quietly = TRUE, verbose = getOption(\"verbose\"), .local_envir = parent.frame() ) with_namespace(package, code, warn.conflicts = FALSE) local_namespace(package, .local_envir = parent.frame(), warn.conflicts = FALSE) with_environment( env, code, pos = 2L, name = format(env), warn.conflicts = FALSE ) local_environment( env, pos = 2L, name = format(env), warn.conflicts = FALSE, .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_package.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Execute code with a modified search path — with_package","text":"package [character(1)] package name load. code [] Code execute temporary environment pos position search list attach loaded namespace. Can also name position current search list given search(). lib.loc character vector describing location R library trees search , NULL. default value NULL corresponds libraries currently known .libPaths(). Non-existent library trees silently ignored. character.logical indicating whether package help can assumed character strings. logical.return logical. TRUE, FALSE TRUE returned indicate success. warn.conflicts logical. TRUE, warnings printed conflicts attaching new package. conflict function masking function, non-function masking non-function. default TRUE unless specified FALSE conflicts.policy option. quietly logical. TRUE, message confirming package attaching printed, often, errors/warnings printed package attaching fails. verbose logical. TRUE, additional diagnostics printed. .local_envir [environment] environment use scoping. env [environment()] Environment attach. name name use attached database. Names starting package: reserved library.","code":""},{"path":"https://withr.r-lib.org/reference/with_package.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Execute code with a modified search path — with_package","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_package.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Execute code with a modified search path — with_package","text":"","code":"if (FALSE) { # \\dontrun{ with_package(\"ggplot2\", { ggplot(mtcars) + geom_point(aes(wt, hp)) }) } # }"},{"path":"https://withr.r-lib.org/reference/with_par.html","id":null,"dir":"Reference","previous_headings":"","what":"Graphics parameters — with_par","title":"Graphics parameters — with_par","text":"Temporarily change graphics parameters.","code":""},{"path":"https://withr.r-lib.org/reference/with_par.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Graphics parameters — with_par","text":"","code":"with_par(new, code, no.readonly = FALSE) local_par( .new = list(), ..., no.readonly = FALSE, .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_par.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Graphics parameters — with_par","text":"new, .new [named list] New graphics parameters values code [] Code execute temporary environment .readonly [logical(1)] see par() documentation. ... Additional graphics parameters values. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_par.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Graphics parameters — with_par","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_par.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Graphics parameters — with_par","text":"","code":"old <- par(\"col\" = \"black\") # This will be in red with_par(list(col = \"red\", pch = 19), plot(mtcars$hp, mtcars$wt) ) # This will still be in black plot(mtcars$hp, mtcars$wt) par(old)"},{"path":"https://withr.r-lib.org/reference/with_path.html","id":null,"dir":"Reference","previous_headings":"","what":"PATH environment variable — with_path","title":"PATH environment variable — with_path","text":"Temporarily change system search path.","code":""},{"path":"https://withr.r-lib.org/reference/with_path.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"PATH environment variable — with_path","text":"","code":"with_path(new, code, action = c(\"prefix\", \"suffix\", \"replace\")) local_path( new = list(), action = c(\"prefix\", \"suffix\", \"replace\"), .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_path.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"PATH environment variable — with_path","text":"new [character] New PATH entries code [] Code execute temporary environment action [character(1)] new values \"replace\", \"prefix\" (default) \"suffix\" existing paths .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_path.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"PATH environment variable — with_path","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_path.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"PATH environment variable — with_path","text":"","code":"# temporarily modify the system PATH, *prefixing* the current path with_path(getwd(), Sys.getenv(\"PATH\")) #> [1] \"/home/runner/work/withr/withr/docs/reference:/opt/hostedtoolcache/pandoc/3.1.11/x64:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin\" # temporarily modify the system PATH, *appending* to the current path with_path(getwd(), Sys.getenv(\"PATH\"), \"suffix\") #> [1] \"/opt/hostedtoolcache/pandoc/3.1.11/x64:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/games:/snap/bin:/home/runner/work/withr/withr/docs/reference\""},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":null,"dir":"Reference","previous_headings":"","what":"RNG version — with_rng_version","title":"RNG version — with_rng_version","text":"Change RNG version restore afterwards.","code":""},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"RNG version — with_rng_version","text":"","code":"with_rng_version(version, code) local_rng_version(version, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"RNG version — with_rng_version","text":"version [character(1)] R version number, e.g. \"3.5.0\", switch RNG version R uses. See RNGversion(). code [] Code execute temporary environment .local_envir environment apply change .","code":""},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"RNG version — with_rng_version","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"RNG version — with_rng_version","text":"with_rng_version() runs code specified RNG version resets afterwards. local_rng_version() changes RNG version caller execution environment.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"RNG version — with_rng_version","text":"","code":"RNGkind() #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rejection\" with_rng_version(\"3.0.0\", RNGkind()) #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rounding\" with_rng_version(\"1.6.0\", RNGkind()) #> [1] \"Marsaglia-Multicarry\" \"Buggy Kinderman-Ramage\" #> [3] \"Rounding\" with_rng_version(\"3.0.0\", with_seed(42, sample(1:100, 3))) #> [1] 92 93 29 with_rng_version(\"1.6.0\", with_seed(42, sample(1:100, 3))) #> Warning: buggy version of Kinderman-Ramage generator used #> Warning: RNGkind: Marsaglia-Multicarry has poor statistical properties #> [1] 33 44 32 RNGkind() #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rejection\" fun1 <- function() { local_rng_version(\"3.0.0\") with_seed(42, sample(1:100, 3)) } fun2 <- function() { local_rng_version(\"1.6.0\") with_seed(42, sample(1:100, 3)) } RNGkind() #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rejection\" fun1() #> [1] 92 93 29 fun2() #> Warning: buggy version of Kinderman-Ramage generator used #> Warning: RNGkind: Marsaglia-Multicarry has poor statistical properties #> [1] 33 44 32 RNGkind() #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rejection\""},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":null,"dir":"Reference","previous_headings":"","what":"Random seed — with_seed","title":"Random seed — with_seed","text":"with_seed() runs code specific random seed resets afterwards. with_preserve_seed() runs code current random seed resets afterwards.","code":""},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Random seed — with_seed","text":"","code":"with_seed( seed, code, .rng_kind = NULL, .rng_normal_kind = NULL, .rng_sample_kind = NULL ) local_seed( seed, .local_envir = parent.frame(), .rng_kind = NULL, .rng_normal_kind = NULL, .rng_sample_kind = NULL ) with_preserve_seed(code) local_preserve_seed(.local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Random seed — with_seed","text":"seed [integer(1)] random seed use evaluate code. code [] Code execute temporary environment .rng_kind, .rng_normal_kind, .rng_sample_kind [character(1)] Kind RNG use. Passed kind, normal.kind, sample.kind arguments RNGkind(). .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Random seed — with_seed","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Random seed — with_seed","text":"","code":"# Same random values: with_preserve_seed(runif(5)) #> [1] 0.10169262 0.76999328 0.08906143 0.53659237 0.26213892 with_preserve_seed(runif(5)) #> [1] 0.10169262 0.76999328 0.08906143 0.53659237 0.26213892 # Use a pseudorandom value as seed to advance the RNG and pick a different # value for the next call: with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5)) #> [1] 0.5885083 0.3289879 0.4357050 0.2184870 0.3697503 with_seed(seed, runif(5)) #> [1] 0.5885083 0.3289879 0.4357050 0.2184870 0.3697503 with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5)) #> [1] 0.6099326 0.6076366 0.4936592 0.6276273 0.5535448"},{"path":"https://withr.r-lib.org/reference/with_sink.html","id":null,"dir":"Reference","previous_headings":"","what":"Output redirection — with_sink","title":"Output redirection — with_sink","text":"Temporarily divert output file via sink(). sinks type message, error raised sink already active.","code":""},{"path":"https://withr.r-lib.org/reference/with_sink.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Output redirection — with_sink","text":"","code":"with_output_sink(new, code, append = FALSE, split = FALSE) local_output_sink( new = list(), append = FALSE, split = FALSE, .local_envir = parent.frame() ) with_message_sink(new, code, append = FALSE) local_message_sink(new = list(), append = FALSE, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_sink.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Output redirection — with_sink","text":"new [character(1)|connection] writable connection character string naming file write . Passing NULL throw error. code [] Code execute temporary environment append logical. TRUE, output appended file; otherwise, overwrite contents file. split logical: TRUE, output sent new sink current output stream, like Unix program tee. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_sink.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Output redirection — with_sink","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_temp_libpaths.html","id":null,"dir":"Reference","previous_headings":"","what":"Library paths — with_temp_libpaths","title":"Library paths — with_temp_libpaths","text":"Temporarily prepend new temporary directory library paths.","code":""},{"path":"https://withr.r-lib.org/reference/with_temp_libpaths.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Library paths — with_temp_libpaths","text":"","code":"with_temp_libpaths(code, action = \"prefix\") local_temp_libpaths(action = \"prefix\", .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_temp_libpaths.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Library paths — with_temp_libpaths","text":"code [] Code execute temporary environment action [character(1)] new values \"replace\", \"prefix\" \"suffix\" existing paths. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_temp_libpaths.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Library paths — with_temp_libpaths","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":null,"dir":"Reference","previous_headings":"","what":"Temporary files and directories — with_tempfile","title":"Temporary files and directories — with_tempfile","text":"Temporarily create file directory, automatically deleted finished .","code":""},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Temporary files and directories — with_tempfile","text":"","code":"with_tempfile( new, code, envir = parent.frame(), .local_envir = parent.frame(), pattern = \"file\", tmpdir = tempdir(), fileext = \"\" ) local_tempfile( new = NULL, lines = NULL, envir = parent.frame(), .local_envir = parent.frame(), pattern = \"file\", tmpdir = tempdir(), fileext = \"\" ) with_tempdir( code, clean = TRUE, pattern = \"file\", tmpdir = tempdir(), fileext = \"\" ) local_tempdir( pattern = \"file\", tmpdir = tempdir(), fileext = \"\", .local_envir = parent.frame(), clean = TRUE )"},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Temporary files and directories — with_tempfile","text":"new [character vector] (Deprecated local_tempfile()) Names temporary file handles create. code [] Code execute temporary environment envir [environment] Deprecated favor .local_envir. .local_envir [environment] environment use scoping. pattern non-empty character vector giving initial part name. tmpdir non-empty character vector giving directory name. fileext non-empty character vector giving file extension. lines Optionally, supply character vector lines written path. useful want seed file default content. clean [logical(1)] logical indicating temporary directory deleted use (TRUE, default) left alone (FALSE).","code":""},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Temporary files and directories — with_tempfile","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Temporary files and directories — with_tempfile","text":"","code":"# local_tempfile() is the easiest to use because it returns a path local({ path1 <<- local_tempfile(lines = c(\"x,y\", \"1,2\")) readLines(path1) }) #> [1] \"x,y\" \"1,2\" # the file is deleted automatically file.exists(path1) #> [1] FALSE # with_tempfile() is a bit trickier; the first argument gives the name # of a variable that will contain the path: with_tempfile(\"path2\", { print(path2) write.csv(iris, path2) file.size(path2) }) #> [1] \"/tmp/Rtmp7gdDMb/file16ae32633ce4\" #> [1] 4821 # Note that this variable is only available in the scope of with_tempfile try(path2) #> Error in eval(expr, envir) : object 'path2' not found"},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":null,"dir":"Reference","previous_headings":"","what":"Time zone — with_timezone","title":"Time zone — with_timezone","text":"Change time zone, restore afterwards.","code":""},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Time zone — with_timezone","text":"","code":"with_timezone(tz, code) local_timezone(tz, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Time zone — with_timezone","text":"tz [character(1)] valid time zone specification, note time zone names might platform dependent. code [] Code execute temporary environment .local_envir environment apply change .","code":""},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Time zone — with_timezone","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Time zone — with_timezone","text":"with_timezone() runs code specified time zone resets afterwards. local_timezone() changes time zone caller execution environment.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Time zone — with_timezone","text":"","code":"Sys.time() #> [1] \"2024-10-28 11:01:04 UTC\" with_timezone(\"Europe/Paris\", print(Sys.time())) #> [1] \"2024-10-28 12:01:04 CET\" with_timezone(\"America/Los_Angeles\", print(Sys.time())) #> [1] \"2024-10-28 04:01:04 PDT\" fun1 <- function() { local_timezone(\"CET\") print(Sys.time()) } fun2 <- function() { local_timezone(\"America/Los_Angeles\") print(Sys.time()) } Sys.time() #> [1] \"2024-10-28 11:01:04 UTC\" fun1() #> [1] \"2024-10-28 12:01:04 CET\" fun2() #> [1] \"2024-10-28 04:01:04 PDT\" Sys.time() #> [1] \"2024-10-28 11:01:04 UTC\""},{"path":"https://withr.r-lib.org/reference/withr.html","id":null,"dir":"Reference","previous_headings":"","what":"Execute code in temporarily altered environment — withr","title":"Execute code in temporarily altered environment — withr","text":"functions prefixed with_ work follows. First, particular aspect global environment modified (see list). , custom code (passed via code argument) executed. Upon completion error, global environment restored previous state. with_ function local_ variant, instead resets state current evaluation context ends (end function).","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/withr.html","id":"usage-pattern","dir":"Reference","previous_headings":"","what":"Usage pattern","title":"Execute code in temporarily altered environment — withr","text":"with_...(new, code, ...)","code":""},{"path":"https://withr.r-lib.org/reference/withr.html","id":"withr-functions","dir":"Reference","previous_headings":"","what":"withr functions","title":"Execute code in temporarily altered environment — withr","text":"with_collate(): collation order with_dir(): working directory with_envvar(): environment variables with_libpaths(): library paths, replacing current libpaths with_locale(): locale setting with_makevars(): Makevars variables with_options(): options with_par(): graphics parameters with_path(): PATH environment variable with_sink(): output redirection","code":""},{"path":"https://withr.r-lib.org/reference/withr.html","id":"creating-new-with-functions","dir":"Reference","previous_headings":"","what":"Creating new \"with\" functions","title":"Execute code in temporarily altered environment — withr","text":"with_ functions created helper function, with_(). functions accepts two arguments: setter function optional resetter function. setter function expected change global state return \"undo instruction\". undo instruction passed resetter function, changes back global state. many cases, setter function can used naturally resetter.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/withr.html","id":"author","dir":"Reference","previous_headings":"","what":"Author","title":"Execute code in temporarily altered environment — withr","text":"Maintainer: Lionel Henry lionel@posit.co Authors: Jim Hester Kirill Müller krlmlr+r@mailbox.org Kevin Ushey kevinushey@gmail.com Hadley Wickham hadley@posit.co Winston Chang contributors: Jennifer Bryan [contributor] Richard Cotton [contributor] Posit Software, PBC [copyright holder, funder]","code":""},{"path":"https://withr.r-lib.org/reference/withr.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Execute code in temporarily altered environment — withr","text":"","code":"getwd() #> [1] \"/home/runner/work/withr/withr/docs/reference\" with_dir(tempdir(), getwd()) #> [1] \"/tmp/Rtmp7gdDMb\" getwd() #> [1] \"/home/runner/work/withr/withr/docs/reference\" 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\" # local variants are best used within other functions f <- function(x) { local_envvar(c(\"WITHR\" = 2)) Sys.getenv(\"WITHR\") } Sys.getenv(\"WITHR\") #> [1] \"\""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-302","dir":"Changelog","previous_headings":"","what":"withr 3.0.2","title":"withr 3.0.2","text":"local_language() now never warns set \"C\" (#254). cross-platform silent way disabling gettext() translations.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-301","dir":"Changelog","previous_headings":"","what":"withr 3.0.1","title":"withr 3.0.1","text":"CRAN release: 2024-07-31 Fixes CRAN checks.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-300","dir":"Changelog","previous_headings":"","what":"withr 3.0.0","title":"withr 3.0.0","text":"CRAN release: 2024-01-16","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"performance-of-withr-3-0-0","dir":"Changelog","previous_headings":"","what":"Performance of withr","title":"withr 3.0.0","text":"defer() now thin wrapper around base::.exit(). possible thanks two contributions made R 3.5: added argument LIFO cleanup: .exit(= FALSE). Calling sys..exit() elsewhere top-level didn’t work. needed manual invocation deferred_run(). Following change, defer() now much faster (although still slower .exit() primitive function fast gets). also increases compatibility defer() .exit() (handlers now run expected order even registered .exit()) standalone versions defer().","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"breaking-change-3-0-0","dir":"Changelog","previous_headings":"","what":"Breaking change","title":"withr 3.0.0","text":"source() used local environment, opposed globalenv() (default), now need set options(withr.hook_source = TRUE) get proper withr support (running defer() local_ functions top-level script). support disabled default local environments avoid performance penalty normal usage withr features.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"other-features-and-bugfixes-3-0-0","dir":"Changelog","previous_headings":"","what":"Other features and bugfixes","title":"withr 3.0.0","text":"deferred_run() now reports number executed expressions message. deferred_run() can now run point knitr file (#235). local_tempfile() now writes lines UTF-8 (#210) always uses \\n newlines (#216). local_pdf() friends now correctly restore previously active device (#138). local_() now works even withr isn’t attached (#207). local_par() with_par() now work don’t set parameters (#238). with_language() now properly resets translation cache (#213). Fixes Debian packaging.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-252","dir":"Changelog","previous_headings":"","what":"withr 2.5.2","title":"withr 2.5.2","text":"CRAN release: 2023-10-30 Fixes CRAN checks.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-251","dir":"Changelog","previous_headings":"","what":"withr 2.5.1","title":"withr 2.5.1","text":"CRAN release: 2023-09-26 Fixes CRAN checks.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-250","dir":"Changelog","previous_headings":"","what":"withr 2.5.0","title":"withr 2.5.0","text":"CRAN release: 2022-03-03 defer() local_*() functions now work run inside .Rmd. deferred expressions executed knitr exits. defer() local_ functions now work within source(). deferred expressions executed source() exits. with_() local_() gain get argument. Supply getter function create local functions robust early exits. supplied, restoration pattern used: Instead : ensures proper restoration old state early exit occurs set() (instance deprecation warning caught, see #191). with_ local_ functions now robust early exits (see next bullet): _locale() _envvar() _libpaths() _options() _par() _path() _seed() with_namespace() local_namespace() now pass warn.conflicts attach() (@kyleam, #185). local_rng_version() local_seed() longer warn restoring sample.kind \"Rounding\" (#167). with_seed() now preserves current values RNGkind() (#167). with_collate() longer affected LC_COLLATE environment variable set “C” (#179). Local evaluations globalenv() (opposed top-level ones) now unwound way regular environments. local_tempfile() gains lines argument , desired, can pre-fill temporary file data.","code":"old <- get() on.exit(set(old)) set(new) action() old <- set(new) on.exit(set(old)) action()"},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-243","dir":"Changelog","previous_headings":"","what":"withr 2.4.3","title":"withr 2.4.3","text":"CRAN release: 2021-11-30 Lionel Henry new maintainer. Handlers registered global environment (happens local_() run top-level, outside function) now automatically run R session ends (#173). New with_language() local_language() temporarily control language used translations (#180). with_seed() now caches check R version, now faster (#170) with_makevars() local_makevars() now eagerly evaluate path argument (#169)","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-242","dir":"Changelog","previous_headings":"","what":"withr 2.4.2","title":"withr 2.4.2","text":"CRAN release: 2021-04-18 local_options() now lets set option NULL intended (#156) local_tempfile() argument envir deprecated, favor .local_envir. withr functions except local_tempfile() used .local_envir specify environments, makes function consistent rest. (#157) with_environment() now passing pos warn.conflicts attach(), intended (#161). with_seed() now also sets RNG via new arguments .rng_kind, .rng_normal_kind .rng_sample_kind (#162, @AshesITR). with_timezone() now works recent changes Sys.timezone() R-devel (#165)","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-241","dir":"Changelog","previous_headings":"","what":"withr 2.4.1","title":"withr 2.4.1","text":"CRAN release: 2021-01-26 Tests require capabilities(\"cairo\") now skipped.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-240","dir":"Changelog","previous_headings":"","what":"withr 2.4.0","title":"withr 2.4.0","text":"CRAN release: 2021-01-16 withr now licensed MIT (#154). Tests with_cairo_pdf() with_cairo_ps() removed, fail Cairo available, M1 macOS systems (#158) local_seed() now exported (#153)","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-230","dir":"Changelog","previous_headings":"","what":"withr 2.3.0","title":"withr 2.3.0","text":"CRAN release: 2020-09-22","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"deprecations-2-3-0","dir":"Changelog","previous_headings":"","what":"Deprecations","title":"withr 2.3.0","text":"local_tempfile() argument new deprecated, favor returning path new tempfile. calls like local_tempfile(\"xyz\") replaced xyx <- local_tempfile() code (#141).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"new-features-2-3-0","dir":"Changelog","previous_headings":"","what":"New features","title":"withr 2.3.0","text":"New local_seed() function local_preserve_seed() functions correspond with_seed() with_preserve_seed() (#139). New local_tempdir() function added create temp directory (#140) local_*() functions now take dots (...), can simplify calls cases, e.g. can now use local_options(foo = \"bar\") rather local_options(c(foo = \"bar\")).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"minor-improvements-and-fixes-2-3-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and fixes","title":"withr 2.3.0","text":"defer() now throws error error occurs deferred expression (#148) with_file() local_file() can now work file actually directory (#144).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-220","dir":"Changelog","previous_headings":"","what":"withr 2.2.0","title":"withr 2.2.0","text":"CRAN release: 2020-04-20 defer() can set deferred events .GlobalEnv facilitate interactive development code inside function test. Helpers deferred_run() (deferred_clear()) provide way explicity run clear (just clear) deferred events (#76, @jennybc). with_connection() now works existing objects connections exist names (#120) with_makevars() now uses tools::makevars_user() determine default user makevars file (#77, @siddharthab). with_options() longer uses .call(), optiosn evaluated exit (#73, @mtmorgan). with_package() longer help argument (#94, @wendtke). with_package() now try detach package already attached calling with_package() (#107) with_preserve_seed() now restores .Random.seed set originally (#124). Add with_rng_version() local_rng_version() functions change version RNG (#90, @gaborcsardi). with_svg() documentation now consistent across R versions (#129) Add with_timezone() local_timezone() functions change time zone (#92, @gaborcsardi). with_tempfile() local_tempfile() now delete recursively directories exit (#84, @meta00).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-212","dir":"Changelog","previous_headings":"","what":"withr 2.1.2","title":"withr 2.1.2","text":"CRAN release: 2018-03-15 set_makevars() now exported (#68, @gaborcsardi). with_temp_libpaths() gains action argument, specify temporary library path added (#66, @krlmlr).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-211","dir":"Changelog","previous_headings":"","what":"withr 2.1.1","title":"withr 2.1.1","text":"CRAN release: 2017-12-19 Fixes test failures testthat 2.0.0 with_file() function automatically remove files.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-210","dir":"Changelog","previous_headings":"","what":"withr 2.1.0","title":"withr 2.1.0","text":"CRAN release: 2017-11-01 with_connection() function automatically close R file connections. with_db_connection() function automatically disconnect DBI database connections. with_gctorture2 command run code gctorture2, useful testing (#47). with_package(), with_namespace() with_environment() (equivalent locals) functions added, run code modified object search path (#38, #48). Add with_tempfile() local_tempfile() functions create temporary files cleanup afterwards. (#32) Remove code argument local_ functions (#50).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-200","dir":"Changelog","previous_headings":"","what":"withr 2.0.0","title":"withr 2.0.0","text":"CRAN release: 2017-07-28 with_ function now local_ variant, reset end local scope, generally end function body. New functions with_seed() with_preserve_seed() running code given random seed (#45, @krlmlr).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-102","dir":"Changelog","previous_headings":"","what":"withr 1.0.2","title":"withr 1.0.2","text":"CRAN release: 2016-06-20 with_makevars() gains assignment argument allow specifying additional assignment types.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-101","dir":"Changelog","previous_headings":"","what":"withr 1.0.1","title":"withr 1.0.1","text":"CRAN release: 2016-02-04 Relaxed R version requirement 3.0.2 (#35, #39). New with_output_sink() with_message_sink() (#24).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-100","dir":"Changelog","previous_headings":"","what":"withr 1.0.0","title":"withr 1.0.0","text":"CRAN release: 2015-09-23 First Public Release","code":""}]
+[{"path":"https://withr.r-lib.org/LICENSE.html","id":null,"dir":"","previous_headings":"","what":"MIT License","title":"MIT License","text":"Copyright (c) 2020 withr authors Permission hereby granted, free charge, person obtaining copy software associated documentation files (“Software”), deal Software without restriction, including without limitation rights use, copy, modify, merge, publish, distribute, sublicense, /sell copies Software, permit persons Software furnished , subject following conditions: copyright notice permission notice shall included copies substantial portions Software. SOFTWARE PROVIDED “”, WITHOUT WARRANTY KIND, EXPRESS IMPLIED, INCLUDING LIMITED WARRANTIES MERCHANTABILITY, FITNESS PARTICULAR PURPOSE NONINFRINGEMENT. EVENT SHALL AUTHORS COPYRIGHT HOLDERS LIABLE CLAIM, DAMAGES LIABILITY, WHETHER ACTION CONTRACT, TORT OTHERWISE, ARISING , CONNECTION SOFTWARE USE DEALINGS SOFTWARE.","code":""},{"path":"https://withr.r-lib.org/MAINTENANCE.html","id":"current-state","dir":"","previous_headings":"","what":"Current state","title":"NA","text":"withr generally works use cases doesn’t need great deal reoccurring maintenance.","code":""},{"path":"https://withr.r-lib.org/MAINTENANCE.html","id":"future-directions","dir":"","previous_headings":"","what":"Future directions","title":"NA","text":"Harmonize implementation similar functinos rlang, already somewhat now compat-defer implementation.","code":""},{"path":"https://withr.r-lib.org/articles/withr.html","id":"its-dangerous-to-change-state","dir":"Articles","previous_headings":"","what":"It’s dangerous to change state","title":"Changing and restoring state","text":"Whenever possible, desirable write -called pure functions. property focus function change surrounding R landscape, .e. change things like search path, global options, working directory. behaviour functions differs running function, ’ve modified landscape. Changing landscape bad makes code much harder understand. ’s sloppy() function prints number specific number significant digits, adjusting R’s global “digits” option. Notice pi prints differently call sloppy()? Calling sloppy() side effect: changes “digits” option globally, just within scope operations. want avoid. Don’t worry, ’re restoring global state (specifically, “digits” option) behind scenes . Sometimes avoid modifying state world, case just make sure put things back way found . withr package .","code":"sloppy <- function(x, sig_digits) { options(digits = sig_digits) print(x) } pi #> [1] 3.141593 sloppy(pi, 2) #> [1] 3.1 pi #> [1] 3.1"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"the-base-solution-on-exit","dir":"Articles","previous_headings":"","what":"The base solution: on.exit()","title":"Changing and restoring state","text":"first function know base R’s .exit(). Inside function body, every time something undone exit, immediately register cleanup code .exit(expr, add = TRUE)1. neat() improvement sloppy(), uses .exit() ensure “digits” option restored original value. .exit() also works exit function abnormally, .e. due error. official tools, like .exit(), better choice --solution problem. .exit() useful function, ’s flexible. withr package provides extensible .exit()-inspired toolkit.","code":"neat <- function(x, sig_digits) { op <- options(digits = sig_digits) on.exit(options(op), add = TRUE) print(x) } pi #> [1] 3.141593 neat(pi, 2) #> [1] 3.1 pi #> [1] 3.141593"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"defer-is-the-foundation-of-withr","dir":"Articles","previous_headings":"","what":"defer() is the foundation of withr","title":"Changing and restoring state","text":"defer() core function withr much like .exit(), .e. schedules execution arbitrary code current function exits: withr::defer() basically drop-substitute .exit(), three key differences explore : Different default behaviour around effect series two calls Control environment deferred events associated Ability work global environment focus using withr inside functions. See blog post Self-cleaning test fixtures testthat vignette Test fixtures use withr inside tests.","code":"neater <- function(x, sig_digits) { op <- options(digits = sig_digits) defer(options(op)) print(x) } pi #> [1] 3.141593 neater(pi, 2) #> [1] 3.1 pi #> [1] 3.141593"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"last-in-first-out","dir":"Articles","previous_headings":"","what":"Last-in, first-out","title":"Changing and restoring state","text":"make one call defer(), default, adds expressions top stack deferred actions. contrast, default, subsequent call .exit() overwrites deferred actions registered previous call. Oops, still socks ! last-, first-, stack-like behaviour defer() tends want applications. get behaviour .exit(), remember call add = TRUE, = FALSE2. Conversely, want defer() first-, first-behaviour, specify priority = \"last\".","code":"defer_stack <- function() { cat(\"put on socks\\n\") defer(cat(\"take off socks\\n\")) cat(\"put on shoes\\n\") defer(cat(\"take off shoes\\n\")) } defer_stack() #> put on socks #> put on shoes #> take off shoes #> take off socks on_exit_last_one_wins <- function() { cat(\"put on socks\\n\") on.exit(cat(\"take off socks\\n\")) cat(\"put on shoes\\n\") on.exit(cat(\"take off shoes\\n\")) } on_exit_last_one_wins() #> put on socks #> put on shoes #> take off shoes on_exit_stack <- function() { cat(\"put on socks\\n\") on.exit(cat(\"take off socks\\n\"), add = TRUE, after = FALSE) cat(\"put on shoes\\n\") on.exit(cat(\"take off shoes\\n\"), add = TRUE, after = FALSE) } on_exit_stack() #> put on socks #> put on shoes #> take off shoes #> take off socks defer_queue <- function() { cat(\"Adam gets in line for ice cream\\n\") defer(cat(\"Adam gets ice cream\\n\"), priority = \"last\") cat(\"Beth gets in line for ice cream\\n\") defer(cat(\"Beth gets ice cream\\n\"), priority = \"last\") } defer_queue() #> Adam gets in line for ice cream #> Beth gets in line for ice cream #> Adam gets ice cream #> Beth gets ice cream"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"local-functions-and-with-functions","dir":"Articles","previous_headings":"","what":"“Local” functions (and “with” functions)","title":"Changing and restoring state","text":".exit() withr::defer() schedule actions executed certain environment goes scope, typically execution environment function. envir argument withr::defer() lets specify different environment, makes possible create customised .exit() extensions. Let’s look neater() function . first two lines typical .exit() maneuvers , order, record original state, arrange eventual restoration, change . real life, can much involved might want wrap logic helper function. can’t wrap .exit() way, ’s way reach back correct parent frame schedule cleanup . defer(), can! custom helper, called local_digits(). can use local_digits() keep manipulation digits local function. can even call local_digits() multiple times inside function. call local_digits() effect next function exits, ever comes first. Certain state changes, modifying global options, come often withr offers pre-made helpers. helpers come two forms: local_*() functions, like one just made, with_*() functions, explain . state change helpers withr likely find useful: didn’t really need write local_digits() helper, built-withr::local_options() also gets job done: local_*() functions target slightly different use case with_*() functions, inspired base R’s () function: with_*() functions best executing small snippet code modified state local_*() functions best modifying state “now function exits” ’s best minimize footprint state modifications. Therefore, use with_*() functions can. forces put lots (indented) code inside with_*(), e.g. function’s body, ’s better use local_*().","code":"neater <- function(x, sig_digits) { op <- options(digits = sig_digits) # record orig. \"digits\" & change \"digits\" defer(options(op)) # schedule restoration of \"digits\" print(x) } local_digits <- function(sig_digits, envir = parent.frame()) { op <- options(digits = sig_digits) defer(options(op), envir = envir) } neato <- function(x, digits) { local_digits(digits) print(x) } pi #> [1] 3.141593 neato(pi, 2) #> [1] 3.1 neato(pi, 4) #> [1] 3.142 neatful <- function(x) { local_digits(1) print(x) local_digits(3) print(x) local_digits(5) print(x) } neatful(pi) #> [1] 3 #> [1] 3.14 #> [1] 3.1416 neatest <- function(x, sig_digits) { local_options(list(digits = sig_digits)) print(x) } pi #> [1] 3.141593 neatest(pi, 2) #> [1] 3.1 neatest(pi, 4) #> [1] 3.142 neat_with <- function(x, sig_digits) { # imagine lots of code here withr::with_options( list(digits = sig_digits), print(x) ) # ... and a lot more code here } neat_local <- function(x, sig_digits) { withr::local_options(list(digits = sig_digits)) print(x) # imagine lots of code here }"},{"path":"https://withr.r-lib.org/articles/withr.html","id":"deferring-events-on-the-global-environment","dir":"Articles","previous_headings":"","what":"Deferring events on the global environment","title":"Changing and restoring state","text":"one last difference withr::defer() .exit(): ability defer events global environment3. first, sounds pretty weird propose scheduling deferred actions global environment. ’s ephemeral, way function execution environments . goes scope rarely, .e. exit R. want ? answer : development purposes. developing functions tests use withr, ’s useful able execute code interactively, without error, ability trigger deferred events. ’s hard develop functions work one way inside function, another way global environment (, worse, throw error). ’s defer() (functions based ) works interactive session. Note example running vignette, doesn’t look exactly ’ll see interactively. defer events global environment first time, get message alerts situation: add subsequent events, message repeated. Since global environment isn’t perishable, like test environment , call deferred_run() explicitly execute deferred events. can also clear , without running, deferred_clear().","code":"library(withr) defer(print(\"hi\")) pi #> [1] 3.141593 # this adds another deferred event, but does not re-message local_digits(3) pi #> [1] 3.14 deferred_run() #> [1] \"hi\" #> Ran 2/2 deferred expressions pi #> [1] 3.141593 defer(print(\"hi\")) #> Setting global deferred event(s). #> i These will be run: #> * Automatically, when the R session ends. #> * On demand, if you call `withr::deferred_run()`. #> i Use `withr::deferred_clear()` to clear them without executing."},{"path":"https://withr.r-lib.org/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Jim Hester. Author. Lionel Henry. Author, maintainer. Kirill Müller. Author. Kevin Ushey. Author. Hadley Wickham. Author. Winston Chang. Author. Jennifer Bryan. Contributor. Richard Cotton. Contributor. . Copyright holder, funder.","code":""},{"path":"https://withr.r-lib.org/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"Hester J, Henry L, Müller K, Ushey K, Wickham H, Chang W (2024). withr: Run Code '' Temporarily Modified Global State. R package version 3.0.2, https://github.com/r-lib/withr#readme, https://withr.r-lib.org.","code":"@Manual{, title = {withr: Run Code 'With' Temporarily Modified Global State}, author = {Jim Hester and Lionel Henry and Kirill Müller and Kevin Ushey and Hadley Wickham and Winston Chang}, year = {2024}, note = {R package version 3.0.2, https://github.com/r-lib/withr#readme}, url = {https://withr.r-lib.org}, }"},{"path":[]},{"path":"https://withr.r-lib.org/index.html","id":"overview","dir":"","previous_headings":"","what":"Overview","title":"Run Code With Temporarily Modified Global State","text":"set functions run code safely temporarily modified global state, withr makes working global state, .e. side effects, less error-prone. Pure functions, sum() function, easy understand reason : always map input output impact workspace. words, pure functions side effects: affected , affect, global state way apart value return. behavior functions affected global state. Consider read.csv() function: takes filename input returns contents output. case, output depends contents file; .e. output affected global state. Functions like deal side effects. purpose withr package help manage side effects code. may want run code secret information, API key, store environment variable. may also want run code certain options, given random-seed, particular working-directory. withr package helps manage situations, , providing functions modify global state temporarily, safely. functions modify one global settings duration block code, automatically reset block completed.","code":""},{"path":"https://withr.r-lib.org/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Run Code With Temporarily Modified Global State","text":"Many functions originally part devtools package, provides simple package limited dependencies provide access functions. with_collate() / local_collate() - collation order with_dir() / local_dir() - working directory with_envvar() / local_envvar() - environment variables with_libpaths() / local_libpaths() - library paths with_locale() / local_locale() - locale setting with_makevars() / local_makevars() / set_makevars() - makevars variables with_options() / local_options() - options with_par() / local_par() - graphics parameters with_path() / local_path() - PATH environment variable with_*() local_*() functions built R devices, bmp, cairo_pdf, cairo_ps, pdf, postscript, svg, tiff, xfig, png, jpeg. with_connection() / local_connection() - R file connections with_db_connection() / local_db_connection() - DB connections with_package() / local_package(), with_namespace() / local_namespace() with_environment() / local_environment() - run code modified object search paths. with_tempfile() / local_tempfile() - create clean temp file. with_file() / local_file() - create clean normal file. with_message_sink() / local_message_sink() - divert message with_output_sink() / local_output_sink() - divert output with_preserve_seed() / with_seed()- specify seeds with_temp_libpaths() / local_temp_libpaths() - library paths defer() / defer_parent() - defer with_timezone() / local_timezone() - timezones with_rng_version() / local_rng_version() - random number generation version","code":"#Install the latest version with: install.packages(\"withr\")"},{"path":"https://withr.r-lib.org/index.html","id":"usage","dir":"","previous_headings":"","what":"Usage","title":"Run Code With Temporarily Modified Global State","text":"two sets functions, prefixed with_ local_. former reset state soon code argument evaluated. latter reset reach end scope, usually end function body. also with_() local_() functions construct new with_* local_* functions needed.","code":"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] \"\" 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\""},{"path":"https://withr.r-lib.org/index.html","id":"see-also","dir":"","previous_headings":"","what":"See Also","title":"Run Code With Temporarily Modified Global State","text":"Devtools","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":null,"dir":"Reference","previous_headings":"","what":"Defer Evaluation of an Expression — defer","title":"Defer Evaluation of an Expression — defer","text":"Similar .exit(), allows one attach expression evaluated exiting frame currently stack. provides nice mechanism scoping side effects duration function's execution.","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Defer Evaluation of an Expression — defer","text":"","code":"defer(expr, envir = parent.frame(), priority = c(\"first\", \"last\")) defer_parent(expr, priority = c(\"first\", \"last\")) deferred_run(envir = parent.frame()) deferred_clear(envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/defer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Defer Evaluation of an Expression — defer","text":"expr [expression] expression evaluated. envir [environment] Attach exit handlers environment. Typically, either current environment parent frame (accessed parent.frame()). priority [character(1)] Specify whether handler executed \"first\" \"last\", relative registered handlers environment.","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Defer Evaluation of an Expression — defer","text":"defer() works attaching handlers requested environment (attribute called \"handlers\"), registering exit handler executes registered handler function associated requested environment finishes execution. Deferred events can set global environment, primarily facilitate interactive development code intended executed inside function test. message alerts user fact explicit deferred_run() way trigger deferred events. Use deferred_clear() clear without evaluation. global environment scenario main motivation functions.","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":"running-handlers-within-source-","dir":"Reference","previous_headings":"","what":"Running handlers within source()","title":"Defer Evaluation of an Expression — defer","text":"withr handlers run within source() run source() exits rather line line. case script sourced globalenv(). local environment, caller needs set options(withr.hook_source = TRUE). avoid paying penalty detecting source() normal usage defer().","code":""},{"path":"https://withr.r-lib.org/reference/defer.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Defer Evaluation of an Expression — defer","text":"","code":"# define a 'local' function that creates a file, and # removes it when the parent function has finished executing local_file <- function(path) { file.create(path) defer_parent(unlink(path)) } # create tempfile path path <- tempfile() # use 'local_file' in a function local({ local_file(path) stopifnot(file.exists(path)) }) # file is deleted as we leave 'local' local stopifnot(!file.exists(path)) # investigate how 'defer' modifies the # executing function's environment local({ local_file(path) print(attributes(environment())) }) #> NULL # Note that examples lack function scoping so deferred calls are # generally executed immediately defer(print(\"one\")) #> [1] \"one\" defer(print(\"two\")) #> [1] \"two\""},{"path":"https://withr.r-lib.org/reference/devices.html","id":null,"dir":"Reference","previous_headings":"","what":"Graphics devices — devices","title":"Graphics devices — devices","text":"Temporarily use graphics device.","code":""},{"path":"https://withr.r-lib.org/reference/devices.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Graphics devices — devices","text":"","code":"with_bmp(new, code, ...) local_bmp(new, ..., .local_envir = parent.frame()) with_cairo_pdf(new, code, ...) local_cairo_pdf(new, ..., .local_envir = parent.frame()) with_cairo_ps(new, code, ...) local_cairo_ps(new, ..., .local_envir = parent.frame()) with_pdf(new, code, ...) local_pdf(new, ..., .local_envir = parent.frame()) with_postscript(new, code, ...) local_postscript(new, ..., .local_envir = parent.frame()) with_svg(new, code, ...) local_svg(new, ..., .local_envir = parent.frame()) with_tiff(new, code, ...) local_tiff(new, ..., .local_envir = parent.frame()) with_xfig(new, code, ...) local_xfig(new, ..., .local_envir = parent.frame()) with_png(new, code, ...) local_png(new, ..., .local_envir = parent.frame()) with_jpeg(new, code, ...) local_jpeg(new, ..., .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/devices.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Graphics devices — devices","text":"new [named character] New graphics device code [] Code execute temporary environment ... Additional arguments passed graphics device. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/devices.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Graphics devices — devices","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/devices.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Graphics devices — devices","text":"with_bmp() local_bmp() wrap around grDevices::bmp(). with_cairo_pdf() local_cairo_pdf() wrap around grDevices::cairo_pdf(). with_cairo_ps() local_cairo_ps() wrap around grDevices::cairo_ps(). with_pdf() local_pdf() wrap around grDevices::pdf(). with_postscript() local_postscript() wrap around grDevices::postscript(). with_svg() local_svg() wrap around grDevices::svg(). with_tiff() local_tiff() wrap around grDevices::tiff(). with_xfig() local_xfig() wrap around grDevices::xfig(). with_png() local_png() wrap around grDevices::png(). with_jpeg() local_jpeg() wrap around grDevices::jpeg().","code":""},{"path":"https://withr.r-lib.org/reference/devices.html","id":"functions","dir":"Reference","previous_headings":"","what":"Functions","title":"Graphics devices — devices","text":"with_bmp(): BMP device with_cairo_pdf(): CAIRO_PDF device with_cairo_ps(): CAIRO_PS device with_pdf(): PDF device with_postscript(): POSTSCRIPT device with_svg(): SVG device with_tiff(): TIFF device with_xfig(): XFIG device with_png(): PNG device with_jpeg(): JPEG device","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/devices.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Graphics devices — devices","text":"","code":"# dimensions are in inches with_pdf(file.path(tempdir(), \"test.pdf\"), width = 7, height = 5, plot(runif(5)) ) # dimensions are in pixels with_png(file.path(tempdir(), \"test.png\"), width = 800, height = 600, plot(runif(5)) )"},{"path":"https://withr.r-lib.org/reference/global_defer.html","id":null,"dir":"Reference","previous_headings":"","what":"Defer expression globally — global_defer","title":"Defer expression globally — global_defer","text":"function mostly internal. exported called standalone defer() implementations defer expressions global environment.","code":""},{"path":"https://withr.r-lib.org/reference/global_defer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Defer expression globally — global_defer","text":"","code":"global_defer(expr, priority = c(\"first\", \"last\"))"},{"path":"https://withr.r-lib.org/reference/global_defer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Defer expression globally — global_defer","text":"expr [expression] expression evaluated. priority [character(1)] Specify whether handler executed \"first\" \"last\", relative registered handlers environment.","code":""},{"path":"https://withr.r-lib.org/reference/makevars_user.html","id":null,"dir":"Reference","previous_headings":"","what":"Shim for tools::makevars_user() — makevars_user","title":"Shim for tools::makevars_user() — makevars_user","text":"Shim tools::makevars_user()","code":""},{"path":"https://withr.r-lib.org/reference/makevars_user.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Shim for tools::makevars_user() — makevars_user","text":"","code":"makevars_user()"},{"path":"https://withr.r-lib.org/reference/set_makevars.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new Makevars file, by adding new variables — set_makevars","title":"Create a new Makevars file, by adding new variables — set_makevars","text":"probably want with_makevars() instead function.","code":""},{"path":"https://withr.r-lib.org/reference/set_makevars.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new Makevars file, by adding new variables — set_makevars","text":"","code":"set_makevars( variables, old_path = makevars_user(), new_path = tempfile(), assignment = c(\"=\", \":=\", \"?=\", \"+=\") )"},{"path":"https://withr.r-lib.org/reference/set_makevars.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new Makevars file, by adding new variables — set_makevars","text":"variables [named character] new variables values old_path [character(1)] location existing Makevars file modify. new_path [character(1)] location new Makevars file assignment [character(1)] assignment type use.","code":""},{"path":"https://withr.r-lib.org/reference/set_makevars.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a new Makevars file, by adding new variables — set_makevars","text":"Unlike with_makevars(), activate new Makevars file, .e. set R_MAKEVARS_USER environment variable.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new ","title":"Create a new ","text":"constructors with_... local_... functions. needed want alter global state covered existing with_... functions, see withr overview.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new ","text":"","code":"local_( set, reset = set, get = NULL, ..., envir = parent.frame(), new = TRUE, dots = FALSE ) with_(set, reset = set, get = NULL, ..., envir = parent.frame(), new = TRUE)"},{"path":"https://withr.r-lib.org/reference/with_.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new ","text":"set [function(...)] Function used set state. return value function old state, passed back reset() function clean state. function can arbitrarily many arguments, replicated formals returned function. reset [function(x)] Function used reset state. first argument can named arbitrarily, arguments default values, \"dots\" argument, supported used: function called reset(old). get [function(...)] Optionally, getter function. supplied, .exit() restoration set calling set. robust edge cases. technical reasons, getter function must interface set, means passed new values well. can safely ignored. ... dots future extensions must empty. envir [environment] Environment returned function. new [logical(1)] Replace first argument set function new? Set FALSE set function optional arguments.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Create a new ","text":"[function(new, code, ...)] function least two arguments, new: New state use code: Code run state. arguments function passed set added returned function. set arguments, new FALSE, returned function code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a new ","text":"with_... functions reset state immediately code argument evaluated. local_... functions reset arguments go scope, usually end function body.","code":""},{"path":"https://withr.r-lib.org/reference/with_.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a new ","text":"","code":"with_(setwd) #> function (new, code) #> { #> old <- setwd(dir = new) #> on.exit(setwd(old)) #> force(code) #> } #> global_stack <- list() set_global_state <- function(state, msg = \"Changing global state.\") { global_stack <- c(list(state), global_stack) message(msg) state } reset_global_state <- function(state) { old_state <- global_stack[[1]] global_stack <- global_stack[-1] stopifnot(identical(state, old_state)) } with_(set_global_state, reset_global_state) #> function (new, code, msg = \"Changing global state.\") #> { #> old <- set_global_state(state = new, msg = msg) #> on.exit(reset_global_state(old)) #> force(code) #> } #> "},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":null,"dir":"Reference","previous_headings":"","what":"Collation Order — with_collate","title":"Collation Order — with_collate","text":"Temporarily change collation order changing value LC_COLLATE locale.","code":""},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Collation Order — with_collate","text":"","code":"with_collate(new, code) local_collate(new = list(), .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Collation Order — with_collate","text":"new [character(1)] New collation order code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Collation Order — with_collate","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_collate.html","id":"examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Collation Order — with_collate","text":"","code":"# Modify collation order: x <- c(\"bernard\", \"bérénice\", \"béatrice\", \"boris\") with_collate(\"fr_FR\", sort(x)) #> [1] \"béatrice\" \"bérénice\" \"bernard\" \"boris\" with_collate(\"C\", sort(x)) #> [1] \"bernard\" \"boris\" \"béatrice\" \"bérénice\""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":null,"dir":"Reference","previous_headings":"","what":"Connections which close themselves — with_connection","title":"Connections which close themselves — with_connection","text":"R file connections automatically closed.","code":""},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Connections which close themselves — with_connection","text":"","code":"with_connection(con, code) local_connection(con, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Connections which close themselves — with_connection","text":"con with_connection() named list connection(s) create. local_connection() code create single connection, returned. code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Connections which close themselves — with_connection","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_connection.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Connections which close themselves — with_connection","text":"","code":"with_connection(list(con = file(\"foo\", \"w\")), { writeLines(c(\"foo\", \"bar\"), con) }) read_foo <- function() { readLines(local_connection(file(\"foo\", \"r\"))) } read_foo() #> [1] \"foo\" \"bar\" unlink(\"foo\")"},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":null,"dir":"Reference","previous_headings":"","what":"DBMS Connections which disconnect themselves. — with_db_connection","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"Connections Database Management Systems automatically disconnect. particular connections created DBI::dbConnect() closed DBI::dbDisconnect().","code":""},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"","code":"with_db_connection(con, code) local_db_connection(con, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"con with_db_connection() named list connection(s) create. local_db_connection() code create single connection, returned. code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_db_connection.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"DBMS Connections which disconnect themselves. — with_db_connection","text":"","code":"db <- tempfile() with_db_connection( list(con = DBI::dbConnect(RSQLite::SQLite(), db)), { DBI::dbWriteTable(con, \"mtcars\", mtcars) }) head_db_table <- function(...) { con <- local_db_connection(DBI::dbConnect(RSQLite::SQLite(), db)) head(DBI::dbReadTable(con, \"mtcars\"), ...) } head_db_table() #> mpg cyl disp hp drat wt qsec vs am gear carb #> 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 #> 2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 #> 3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 #> 4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 #> 5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 #> 6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 unlink(db)"},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":null,"dir":"Reference","previous_headings":"","what":"Working directory — with_dir","title":"Working directory — with_dir","text":"Temporarily change current working directory.","code":""},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Working directory — with_dir","text":"","code":"with_dir(new, code) local_dir(new = list(), .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Working directory — with_dir","text":"new [character(1)] New working directory code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Working directory — with_dir","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_dir.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Working directory — with_dir","text":"","code":"getwd() #> [1] \"/home/runner/work/withr/withr/docs/reference\" with_dir(tempdir(), getwd()) #> [1] \"/tmp/RtmpcHnEKr\""},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":null,"dir":"Reference","previous_headings":"","what":"Environment variables — with_envvar","title":"Environment variables — with_envvar","text":"Temporarily change system environment variables.","code":""},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Environment variables — with_envvar","text":"","code":"with_envvar(new, code, action = \"replace\") local_envvar( .new = list(), ..., action = \"replace\", .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Environment variables — with_envvar","text":"new, .new [named character] New environment variables code [] Code execute temporary environment action new values \"replace\", \"prefix\" \"suffix\" existing variables name. ... Named arguments new environment variables. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Environment variables — with_envvar","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Environment variables — with_envvar","text":"NA used environment variables unset. duplicated variable names last one used.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_envvar.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Environment variables — with_envvar","text":"","code":"with_envvar(new = c(\"GITHUB_PAT\" = \"abcdef\"), Sys.getenv(\"GITHUB_PAT\")) #> [1] \"abcdef\" # with_envvar unsets variables after usage Sys.getenv(\"TEMP_SECRET\") #> [1] \"\" with_envvar(new = c(\"TEMP_SECRET\" = \"secret\"), Sys.getenv(\"TEMP_SECRET\")) #> [1] \"secret\" Sys.getenv(\"TEMP_SECRET\") #> [1] \"\""},{"path":"https://withr.r-lib.org/reference/with_file.html","id":null,"dir":"Reference","previous_headings":"","what":"Files which delete themselves — with_file","title":"Files which delete themselves — with_file","text":"Create files, automatically removed afterwards.","code":""},{"path":"https://withr.r-lib.org/reference/with_file.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Files which delete themselves — with_file","text":"","code":"with_file(file, code) local_file(.file, ..., .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_file.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Files which delete themselves — with_file","text":"file, .file [named list] Files create. code [] Code execute temporary environment ... Additional (possibly named) arguments files create. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_file.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Files which delete themselves — with_file","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_file.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Files which delete themselves — with_file","text":"","code":"with_file(\"file1\", { writeLines(\"foo\", \"file1\") readLines(\"file1\") }) with_file(list(\"file1\" = writeLines(\"foo\", \"file1\")), { readLines(\"file1\") })"},{"path":"https://withr.r-lib.org/reference/with_gctorture2.html","id":null,"dir":"Reference","previous_headings":"","what":"Torture Garbage Collector — with_gctorture2","title":"Torture Garbage Collector — with_gctorture2","text":"Temporarily turn gctorture2 .","code":""},{"path":"https://withr.r-lib.org/reference/with_gctorture2.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Torture Garbage Collector — with_gctorture2","text":"","code":"with_gctorture2(new, code, wait = new, inhibit_release = FALSE)"},{"path":"https://withr.r-lib.org/reference/with_gctorture2.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Torture Garbage Collector — with_gctorture2","text":"new [integer] run GC every 'step' allocations. code [] Code execute temporary environment wait integer; number allocations wait starting GC torture. inhibit_release logical; release free objects re-use: use caution.","code":""},{"path":"https://withr.r-lib.org/reference/with_gctorture2.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Torture Garbage Collector — with_gctorture2","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_language.html","id":null,"dir":"Reference","previous_headings":"","what":"Language — with_language","title":"Language — with_language","text":"Temporarily change language used translations.","code":""},{"path":"https://withr.r-lib.org/reference/with_language.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Language — with_language","text":"","code":"with_language(lang, code) local_language(lang, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_language.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Language — with_language","text":"lang BCP47 language code like \"en\" (English), \"fr\" (French), \"fr_CA\" (French Canadian). Formally, lower case two letter ISO 639 country code, optionally followed \"_\" \"-\" upper case two letter ISO 3166 region code. code [] Code execute temporary environment .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_language.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Language — with_language","text":"","code":"with_language(\"en\", try(mean[[1]])) #> Error in mean[[1]] : object of type 'closure' is not subsettable with_language(\"fr\", try(mean[[1]])) #> Error in mean[[1]] : objet de type 'closure' non indiçable with_language(\"es\", try(mean[[1]])) #> Error in mean[[1]] : objeto de tipo 'closure' no es subconjunto"},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":null,"dir":"Reference","previous_headings":"","what":"Library paths — with_libpaths","title":"Library paths — with_libpaths","text":"Temporarily change library paths.","code":""},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Library paths — with_libpaths","text":"","code":"with_libpaths(new, code, action = \"replace\") local_libpaths(new = list(), action = \"replace\", .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Library paths — with_libpaths","text":"new [character] New library paths code [] Code execute temporary environment action [character(1)] new values \"replace\", \"prefix\" \"suffix\" existing paths. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Library paths — with_libpaths","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_libpaths.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Library paths — with_libpaths","text":"","code":".libPaths() #> [1] \"/home/runner/work/_temp/Library\" \"/opt/R/4.4.1/lib/R/site-library\" #> [3] \"/opt/R/4.4.1/lib/R/library\" new_lib <- tempfile() dir.create(new_lib) with_libpaths(new_lib, print(.libPaths())) #> [1] \"/tmp/RtmpcHnEKr/file162e4dce150e\" \"/opt/R/4.4.1/lib/R/site-library\" #> [3] \"/opt/R/4.4.1/lib/R/library\" unlink(new_lib, recursive = TRUE)"},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":null,"dir":"Reference","previous_headings":"","what":"Locale settings — with_locale","title":"Locale settings — with_locale","text":"Temporarily change locale settings.","code":""},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Locale settings — with_locale","text":"","code":"with_locale(new, code) local_locale(.new = list(), ..., .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Locale settings — with_locale","text":"new, .new [named character] New locale settings code [] Code execute temporary environment ... Additional arguments locale settings. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Locale settings — with_locale","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Locale settings — with_locale","text":"Setting LC_ALL category currently implemented.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_locale.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Locale settings — with_locale","text":"","code":"## Change locale for time: df <- data.frame( stringsAsFactors = FALSE, date = as.Date(c(\"2019-01-01\", \"2019-02-01\")), value = c(1, 2) ) with_locale(new = c(\"LC_TIME\" = \"es_ES\"), code = plot(df$date, df$value)) #> Warning: OS reports request to set locale to \"es_ES\" cannot be honored ## Compare with: # plot(df$date, df$value) ## Month names: with_locale(new = c(\"LC_TIME\" = \"en_GB\"), format(ISOdate(2000, 1:12, 1), \"%B\")) #> Warning: OS reports request to set locale to \"en_GB\" cannot be honored #> [1] \"January\" \"February\" \"March\" \"April\" \"May\" #> [6] \"June\" \"July\" \"August\" \"September\" \"October\" #> [11] \"November\" \"December\" with_locale(new = c(\"LC_TIME\" = \"es_ES\"), format(ISOdate(2000, 1:12, 1), \"%B\")) #> Warning: OS reports request to set locale to \"es_ES\" cannot be honored #> [1] \"January\" \"February\" \"March\" \"April\" \"May\" #> [6] \"June\" \"July\" \"August\" \"September\" \"October\" #> [11] \"November\" \"December\" ## Change locale for currencies: with_locale(new = c(\"LC_MONETARY\" = \"it_IT\"), Sys.localeconv()) #> Warning: OS reports request to set locale to \"it_IT\" cannot be honored #> decimal_point thousands_sep grouping int_curr_symbol #> \".\" \"\" \"\" \"\" #> currency_symbol mon_decimal_point mon_thousands_sep mon_grouping #> \"\" \"\" \"\" \"\" #> positive_sign negative_sign int_frac_digits frac_digits #> \"\" \"\" \"127\" \"127\" #> p_cs_precedes p_sep_by_space n_cs_precedes n_sep_by_space #> \"127\" \"127\" \"127\" \"127\" #> p_sign_posn n_sign_posn #> \"127\" \"127\" with_locale(new = c(\"LC_MONETARY\" = \"en_US\"), Sys.localeconv()) #> Warning: OS reports request to set locale to \"en_US\" cannot be honored #> decimal_point thousands_sep grouping int_curr_symbol #> \".\" \"\" \"\" \"\" #> currency_symbol mon_decimal_point mon_thousands_sep mon_grouping #> \"\" \"\" \"\" \"\" #> positive_sign negative_sign int_frac_digits frac_digits #> \"\" \"\" \"127\" \"127\" #> p_cs_precedes p_sep_by_space n_cs_precedes n_sep_by_space #> \"127\" \"127\" \"127\" \"127\" #> p_sign_posn n_sign_posn #> \"127\" \"127\" ## Ordering: x <- c(\"bernard\", \"bérénice\", \"béatrice\", \"boris\") with_locale(c(LC_COLLATE = \"fr_FR\"), sort(x)) #> Warning: OS reports request to set locale to \"fr_FR\" cannot be honored #> [1] \"bernard\" \"boris\" \"béatrice\" \"bérénice\" with_locale(c(LC_COLLATE = \"C\"), sort(x)) #> [1] \"bernard\" \"boris\" \"béatrice\" \"bérénice\""},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":null,"dir":"Reference","previous_headings":"","what":"Makevars variables — with_makevars","title":"Makevars variables — with_makevars","text":"Temporarily change contents existing Makevars file.","code":""},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Makevars variables — with_makevars","text":"","code":"with_makevars( new, code, path = makevars_user(), assignment = c(\"=\", \":=\", \"?=\", \"+=\") ) local_makevars( .new = list(), ..., .path = makevars_user(), .assignment = c(\"=\", \":=\", \"?=\", \"+=\"), .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Makevars variables — with_makevars","text":"new, .new [named character] New variables values code [] Code execute temporary environment path, .path [character(1)] location existing Makevars file modify. assignment, .assignment [character(1)] assignment type use. ... Additional new variables values. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Makevars variables — with_makevars","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Makevars variables — with_makevars","text":"Makevars file exists fields new exist existing Makevars file fields added new file. Existing fields included new appended unchanged. Fields exist Makevars new modified use value new.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_makevars.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Makevars variables — with_makevars","text":"","code":"writeLines(\"void foo(int* bar) { *bar = 1; }\\n\", \"foo.c\") system(\"R CMD SHLIB --preclean -c foo.c\") with_makevars(c(CFLAGS = \"-O3\"), system(\"R CMD SHLIB --preclean -c foo.c\")) unlink(c(\"foo.c\", \"foo.so\"))"},{"path":"https://withr.r-lib.org/reference/with_options.html","id":null,"dir":"Reference","previous_headings":"","what":"Options — with_options","title":"Options — with_options","text":"Temporarily change global options.","code":""},{"path":"https://withr.r-lib.org/reference/with_options.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Options — with_options","text":"","code":"with_options(new, code) local_options(.new = list(), ..., .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_options.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Options — with_options","text":"new, .new [named list] New options values code [] Code execute temporary environment ... Additional options values .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_options.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Options — with_options","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_options.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Options — with_options","text":"","code":"# number of significant digits to print getOption(\"digits\") #> [1] 7 # modify temporarily the number of significant digits to print with_options(list(digits = 3), getOption(\"digits\")) #> [1] 3 with_options(list(digits = 3), print(pi)) #> [1] 3.14 # modify temporarily the character to be used as the decimal point getOption(\"digits\") #> [1] 7 with_options(list(OutDec = \",\"), print(pi)) #> [1] 3,141593 # modify temporarily multiple options with_options(list(OutDec = \",\", digits = 3), print(pi)) #> [1] 3,14 # modify, within the scope of the function, the number of # significant digits to print print_3_digits <- function(x) { # assign 3 to the option \"digits\" for the rest of this function # after the function exits, the option will return to its previous # value local_options(list(digits = 3)) print(x) } print_3_digits(pi) # returns 3.14 #> [1] 3.14 print(pi) # returns 3.141593 #> [1] 3.141593"},{"path":"https://withr.r-lib.org/reference/with_package.html","id":null,"dir":"Reference","previous_headings":"","what":"Execute code with a modified search path — with_package","title":"Execute code with a modified search path — with_package","text":"with_package() attaches package search path, executes code, removes package search path. package namespace unloaded however. with_namespace() thing, attaches package namespace search path, objects (even unexported ones) also available search path.","code":""},{"path":"https://withr.r-lib.org/reference/with_package.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Execute code with a modified search path — with_package","text":"","code":"with_package( package, code, pos = 2, lib.loc = NULL, character.only = TRUE, logical.return = FALSE, warn.conflicts = FALSE, quietly = TRUE, verbose = getOption(\"verbose\") ) local_package( package, pos = 2, lib.loc = NULL, character.only = TRUE, logical.return = FALSE, warn.conflicts = FALSE, quietly = TRUE, verbose = getOption(\"verbose\"), .local_envir = parent.frame() ) with_namespace(package, code, warn.conflicts = FALSE) local_namespace(package, .local_envir = parent.frame(), warn.conflicts = FALSE) with_environment( env, code, pos = 2L, name = format(env), warn.conflicts = FALSE ) local_environment( env, pos = 2L, name = format(env), warn.conflicts = FALSE, .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_package.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Execute code with a modified search path — with_package","text":"package [character(1)] package name load. code [] Code execute temporary environment pos position search list attach loaded namespace. Can also name position current search list given search(). lib.loc character vector describing location R library trees search , NULL. default value NULL corresponds libraries currently known .libPaths(). Non-existent library trees silently ignored. character.logical indicating whether package help can assumed character strings. logical.return logical. TRUE, FALSE TRUE returned indicate success. warn.conflicts logical. TRUE, warnings printed conflicts attaching new package. conflict function masking function, non-function masking non-function. default TRUE unless specified FALSE conflicts.policy option. quietly logical. TRUE, message confirming package attaching printed, often, errors/warnings printed package attaching fails. verbose logical. TRUE, additional diagnostics printed. .local_envir [environment] environment use scoping. env [environment()] Environment attach. name name use attached database. Names starting package: reserved library.","code":""},{"path":"https://withr.r-lib.org/reference/with_package.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Execute code with a modified search path — with_package","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_package.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Execute code with a modified search path — with_package","text":"","code":"if (FALSE) { # \\dontrun{ with_package(\"ggplot2\", { ggplot(mtcars) + geom_point(aes(wt, hp)) }) } # }"},{"path":"https://withr.r-lib.org/reference/with_par.html","id":null,"dir":"Reference","previous_headings":"","what":"Graphics parameters — with_par","title":"Graphics parameters — with_par","text":"Temporarily change graphics parameters.","code":""},{"path":"https://withr.r-lib.org/reference/with_par.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Graphics parameters — with_par","text":"","code":"with_par(new, code, no.readonly = FALSE) local_par( .new = list(), ..., no.readonly = FALSE, .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_par.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Graphics parameters — with_par","text":"new, .new [named list] New graphics parameters values code [] Code execute temporary environment .readonly [logical(1)] see par() documentation. ... Additional graphics parameters values. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_par.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Graphics parameters — with_par","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_par.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Graphics parameters — with_par","text":"","code":"old <- par(\"col\" = \"black\") # This will be in red with_par(list(col = \"red\", pch = 19), plot(mtcars$hp, mtcars$wt) ) # This will still be in black plot(mtcars$hp, mtcars$wt) par(old)"},{"path":"https://withr.r-lib.org/reference/with_path.html","id":null,"dir":"Reference","previous_headings":"","what":"PATH environment variable — with_path","title":"PATH environment variable — with_path","text":"Temporarily change system search path.","code":""},{"path":"https://withr.r-lib.org/reference/with_path.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"PATH environment variable — with_path","text":"","code":"with_path(new, code, action = c(\"prefix\", \"suffix\", \"replace\")) local_path( new = list(), action = c(\"prefix\", \"suffix\", \"replace\"), .local_envir = parent.frame() )"},{"path":"https://withr.r-lib.org/reference/with_path.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"PATH environment variable — with_path","text":"new [character] New PATH entries code [] Code execute temporary environment action [character(1)] new values \"replace\", \"prefix\" (default) \"suffix\" existing paths .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_path.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"PATH environment variable — with_path","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_path.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"PATH environment variable — with_path","text":"","code":"# temporarily modify the system PATH, *prefixing* the current path with_path(getwd(), Sys.getenv(\"PATH\")) #> [1] \"/home/runner/work/withr/withr/docs/reference:/opt/hostedtoolcache/pandoc/3.1.11/x64:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin\" # temporarily modify the system PATH, *appending* to the current path with_path(getwd(), Sys.getenv(\"PATH\"), \"suffix\") #> [1] \"/opt/hostedtoolcache/pandoc/3.1.11/x64:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/games:/snap/bin:/home/runner/work/withr/withr/docs/reference\""},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":null,"dir":"Reference","previous_headings":"","what":"RNG version — with_rng_version","title":"RNG version — with_rng_version","text":"Change RNG version restore afterwards.","code":""},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"RNG version — with_rng_version","text":"","code":"with_rng_version(version, code) local_rng_version(version, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"RNG version — with_rng_version","text":"version [character(1)] R version number, e.g. \"3.5.0\", switch RNG version R uses. See RNGversion(). code [] Code execute temporary environment .local_envir environment apply change .","code":""},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"RNG version — with_rng_version","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"RNG version — with_rng_version","text":"with_rng_version() runs code specified RNG version resets afterwards. local_rng_version() changes RNG version caller execution environment.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_rng_version.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"RNG version — with_rng_version","text":"","code":"RNGkind() #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rejection\" with_rng_version(\"3.0.0\", RNGkind()) #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rounding\" with_rng_version(\"1.6.0\", RNGkind()) #> [1] \"Marsaglia-Multicarry\" \"Buggy Kinderman-Ramage\" #> [3] \"Rounding\" with_rng_version(\"3.0.0\", with_seed(42, sample(1:100, 3))) #> [1] 92 93 29 with_rng_version(\"1.6.0\", with_seed(42, sample(1:100, 3))) #> Warning: buggy version of Kinderman-Ramage generator used #> Warning: RNGkind: Marsaglia-Multicarry has poor statistical properties #> [1] 33 44 32 RNGkind() #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rejection\" fun1 <- function() { local_rng_version(\"3.0.0\") with_seed(42, sample(1:100, 3)) } fun2 <- function() { local_rng_version(\"1.6.0\") with_seed(42, sample(1:100, 3)) } RNGkind() #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rejection\" fun1() #> [1] 92 93 29 fun2() #> Warning: buggy version of Kinderman-Ramage generator used #> Warning: RNGkind: Marsaglia-Multicarry has poor statistical properties #> [1] 33 44 32 RNGkind() #> [1] \"Mersenne-Twister\" \"Inversion\" \"Rejection\""},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":null,"dir":"Reference","previous_headings":"","what":"Random seed — with_seed","title":"Random seed — with_seed","text":"with_seed() runs code specific random seed resets afterwards. with_preserve_seed() runs code current random seed resets afterwards.","code":""},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Random seed — with_seed","text":"","code":"with_seed( seed, code, .rng_kind = NULL, .rng_normal_kind = NULL, .rng_sample_kind = NULL ) local_seed( seed, .local_envir = parent.frame(), .rng_kind = NULL, .rng_normal_kind = NULL, .rng_sample_kind = NULL ) with_preserve_seed(code) local_preserve_seed(.local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Random seed — with_seed","text":"seed [integer(1)] random seed use evaluate code. code [] Code execute temporary environment .rng_kind, .rng_normal_kind, .rng_sample_kind [character(1)] Kind RNG use. Passed kind, normal.kind, sample.kind arguments RNGkind(). .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Random seed — with_seed","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_seed.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Random seed — with_seed","text":"","code":"# Same random values: with_preserve_seed(runif(5)) #> [1] 0.10169262 0.76999328 0.08906143 0.53659237 0.26213892 with_preserve_seed(runif(5)) #> [1] 0.10169262 0.76999328 0.08906143 0.53659237 0.26213892 # Use a pseudorandom value as seed to advance the RNG and pick a different # value for the next call: with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5)) #> [1] 0.5885083 0.3289879 0.4357050 0.2184870 0.3697503 with_seed(seed, runif(5)) #> [1] 0.5885083 0.3289879 0.4357050 0.2184870 0.3697503 with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5)) #> [1] 0.6099326 0.6076366 0.4936592 0.6276273 0.5535448"},{"path":"https://withr.r-lib.org/reference/with_sink.html","id":null,"dir":"Reference","previous_headings":"","what":"Output redirection — with_sink","title":"Output redirection — with_sink","text":"Temporarily divert output file via sink(). sinks type message, error raised sink already active.","code":""},{"path":"https://withr.r-lib.org/reference/with_sink.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Output redirection — with_sink","text":"","code":"with_output_sink(new, code, append = FALSE, split = FALSE) local_output_sink( new = list(), append = FALSE, split = FALSE, .local_envir = parent.frame() ) with_message_sink(new, code, append = FALSE) local_message_sink(new = list(), append = FALSE, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_sink.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Output redirection — with_sink","text":"new [character(1)|connection] writable connection character string naming file write . Passing NULL throw error. code [] Code execute temporary environment append logical. TRUE, output appended file; otherwise, overwrite contents file. split logical: TRUE, output sent new sink current output stream, like Unix program tee. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_sink.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Output redirection — with_sink","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_temp_libpaths.html","id":null,"dir":"Reference","previous_headings":"","what":"Library paths — with_temp_libpaths","title":"Library paths — with_temp_libpaths","text":"Temporarily prepend new temporary directory library paths.","code":""},{"path":"https://withr.r-lib.org/reference/with_temp_libpaths.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Library paths — with_temp_libpaths","text":"","code":"with_temp_libpaths(code, action = \"prefix\") local_temp_libpaths(action = \"prefix\", .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_temp_libpaths.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Library paths — with_temp_libpaths","text":"code [] Code execute temporary environment action [character(1)] new values \"replace\", \"prefix\" \"suffix\" existing paths. .local_envir [environment] environment use scoping.","code":""},{"path":"https://withr.r-lib.org/reference/with_temp_libpaths.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Library paths — with_temp_libpaths","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":null,"dir":"Reference","previous_headings":"","what":"Temporary files and directories — with_tempfile","title":"Temporary files and directories — with_tempfile","text":"Temporarily create file directory, automatically deleted finished .","code":""},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Temporary files and directories — with_tempfile","text":"","code":"with_tempfile( new, code, envir = parent.frame(), .local_envir = parent.frame(), pattern = \"file\", tmpdir = tempdir(), fileext = \"\" ) local_tempfile( new = NULL, lines = NULL, envir = parent.frame(), .local_envir = parent.frame(), pattern = \"file\", tmpdir = tempdir(), fileext = \"\" ) with_tempdir( code, clean = TRUE, pattern = \"file\", tmpdir = tempdir(), fileext = \"\" ) local_tempdir( pattern = \"file\", tmpdir = tempdir(), fileext = \"\", .local_envir = parent.frame(), clean = TRUE )"},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Temporary files and directories — with_tempfile","text":"new [character vector] (Deprecated local_tempfile()) Names temporary file handles create. code [] Code execute temporary environment envir [environment] Deprecated favor .local_envir. .local_envir [environment] environment use scoping. pattern non-empty character vector giving initial part name. tmpdir non-empty character vector giving directory name. fileext non-empty character vector giving file extension. lines Optionally, supply character vector lines written path. useful want seed file default content. clean [logical(1)] logical indicating temporary directory deleted use (TRUE, default) left alone (FALSE).","code":""},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Temporary files and directories — with_tempfile","text":"[] results evaluation code argument.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_tempfile.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Temporary files and directories — with_tempfile","text":"","code":"# local_tempfile() is the easiest to use because it returns a path local({ path1 <<- local_tempfile(lines = c(\"x,y\", \"1,2\")) readLines(path1) }) #> [1] \"x,y\" \"1,2\" # the file is deleted automatically file.exists(path1) #> [1] FALSE # with_tempfile() is a bit trickier; the first argument gives the name # of a variable that will contain the path: with_tempfile(\"path2\", { print(path2) write.csv(iris, path2) file.size(path2) }) #> [1] \"/tmp/RtmpcHnEKr/file162e6262be36\" #> [1] 4821 # Note that this variable is only available in the scope of with_tempfile try(path2) #> Error in eval(expr, envir) : object 'path2' not found"},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":null,"dir":"Reference","previous_headings":"","what":"Time zone — with_timezone","title":"Time zone — with_timezone","text":"Change time zone, restore afterwards.","code":""},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Time zone — with_timezone","text":"","code":"with_timezone(tz, code) local_timezone(tz, .local_envir = parent.frame())"},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Time zone — with_timezone","text":"tz [character(1)] valid time zone specification, note time zone names might platform dependent. code [] Code execute temporary environment .local_envir environment apply change .","code":""},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Time zone — with_timezone","text":"[] results evaluation code argument.","code":""},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Time zone — with_timezone","text":"with_timezone() runs code specified time zone resets afterwards. local_timezone() changes time zone caller execution environment.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/with_timezone.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Time zone — with_timezone","text":"","code":"Sys.time() #> [1] \"2024-10-28 14:34:37 UTC\" with_timezone(\"Europe/Paris\", print(Sys.time())) #> [1] \"2024-10-28 15:34:37 CET\" with_timezone(\"America/Los_Angeles\", print(Sys.time())) #> [1] \"2024-10-28 07:34:37 PDT\" fun1 <- function() { local_timezone(\"CET\") print(Sys.time()) } fun2 <- function() { local_timezone(\"America/Los_Angeles\") print(Sys.time()) } Sys.time() #> [1] \"2024-10-28 14:34:37 UTC\" fun1() #> [1] \"2024-10-28 15:34:37 CET\" fun2() #> [1] \"2024-10-28 07:34:37 PDT\" Sys.time() #> [1] \"2024-10-28 14:34:37 UTC\""},{"path":"https://withr.r-lib.org/reference/withr.html","id":null,"dir":"Reference","previous_headings":"","what":"Execute code in temporarily altered environment — withr","title":"Execute code in temporarily altered environment — withr","text":"functions prefixed with_ work follows. First, particular aspect global environment modified (see list). , custom code (passed via code argument) executed. Upon completion error, global environment restored previous state. with_ function local_ variant, instead resets state current evaluation context ends (end function).","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/withr.html","id":"usage-pattern","dir":"Reference","previous_headings":"","what":"Usage pattern","title":"Execute code in temporarily altered environment — withr","text":"with_...(new, code, ...)","code":""},{"path":"https://withr.r-lib.org/reference/withr.html","id":"withr-functions","dir":"Reference","previous_headings":"","what":"withr functions","title":"Execute code in temporarily altered environment — withr","text":"with_collate(): collation order with_dir(): working directory with_envvar(): environment variables with_libpaths(): library paths, replacing current libpaths with_locale(): locale setting with_makevars(): Makevars variables with_options(): options with_par(): graphics parameters with_path(): PATH environment variable with_sink(): output redirection","code":""},{"path":"https://withr.r-lib.org/reference/withr.html","id":"creating-new-with-functions","dir":"Reference","previous_headings":"","what":"Creating new \"with\" functions","title":"Execute code in temporarily altered environment — withr","text":"with_ functions created helper function, with_(). functions accepts two arguments: setter function optional resetter function. setter function expected change global state return \"undo instruction\". undo instruction passed resetter function, changes back global state. many cases, setter function can used naturally resetter.","code":""},{"path":[]},{"path":"https://withr.r-lib.org/reference/withr.html","id":"author","dir":"Reference","previous_headings":"","what":"Author","title":"Execute code in temporarily altered environment — withr","text":"Maintainer: Lionel Henry lionel@posit.co Authors: Jim Hester Kirill Müller krlmlr+r@mailbox.org Kevin Ushey kevinushey@gmail.com Hadley Wickham hadley@posit.co Winston Chang contributors: Jennifer Bryan [contributor] Richard Cotton [contributor] Posit Software, PBC [copyright holder, funder]","code":""},{"path":"https://withr.r-lib.org/reference/withr.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Execute code in temporarily altered environment — withr","text":"","code":"getwd() #> [1] \"/home/runner/work/withr/withr/docs/reference\" with_dir(tempdir(), getwd()) #> [1] \"/tmp/RtmpcHnEKr\" getwd() #> [1] \"/home/runner/work/withr/withr/docs/reference\" 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\" # local variants are best used within other functions f <- function(x) { local_envvar(c(\"WITHR\" = 2)) Sys.getenv(\"WITHR\") } Sys.getenv(\"WITHR\") #> [1] \"\""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-302","dir":"Changelog","previous_headings":"","what":"withr 3.0.2","title":"withr 3.0.2","text":"CRAN release: 2024-10-28 local_language() now never warns set \"C\" (#254). cross-platform silent way disabling gettext() translations.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-301","dir":"Changelog","previous_headings":"","what":"withr 3.0.1","title":"withr 3.0.1","text":"CRAN release: 2024-07-31 Fixes CRAN checks.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-300","dir":"Changelog","previous_headings":"","what":"withr 3.0.0","title":"withr 3.0.0","text":"CRAN release: 2024-01-16","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"performance-of-withr-3-0-0","dir":"Changelog","previous_headings":"","what":"Performance of withr","title":"withr 3.0.0","text":"defer() now thin wrapper around base::.exit(). possible thanks two contributions made R 3.5: added argument LIFO cleanup: .exit(= FALSE). Calling sys..exit() elsewhere top-level didn’t work. needed manual invocation deferred_run(). Following change, defer() now much faster (although still slower .exit() primitive function fast gets). also increases compatibility defer() .exit() (handlers now run expected order even registered .exit()) standalone versions defer().","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"breaking-change-3-0-0","dir":"Changelog","previous_headings":"","what":"Breaking change","title":"withr 3.0.0","text":"source() used local environment, opposed globalenv() (default), now need set options(withr.hook_source = TRUE) get proper withr support (running defer() local_ functions top-level script). support disabled default local environments avoid performance penalty normal usage withr features.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"other-features-and-bugfixes-3-0-0","dir":"Changelog","previous_headings":"","what":"Other features and bugfixes","title":"withr 3.0.0","text":"deferred_run() now reports number executed expressions message. deferred_run() can now run point knitr file (#235). local_tempfile() now writes lines UTF-8 (#210) always uses \\n newlines (#216). local_pdf() friends now correctly restore previously active device (#138). local_() now works even withr isn’t attached (#207). local_par() with_par() now work don’t set parameters (#238). with_language() now properly resets translation cache (#213). Fixes Debian packaging.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-252","dir":"Changelog","previous_headings":"","what":"withr 2.5.2","title":"withr 2.5.2","text":"CRAN release: 2023-10-30 Fixes CRAN checks.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-251","dir":"Changelog","previous_headings":"","what":"withr 2.5.1","title":"withr 2.5.1","text":"CRAN release: 2023-09-26 Fixes CRAN checks.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-250","dir":"Changelog","previous_headings":"","what":"withr 2.5.0","title":"withr 2.5.0","text":"CRAN release: 2022-03-03 defer() local_*() functions now work run inside .Rmd. deferred expressions executed knitr exits. defer() local_ functions now work within source(). deferred expressions executed source() exits. with_() local_() gain get argument. Supply getter function create local functions robust early exits. supplied, restoration pattern used: Instead : ensures proper restoration old state early exit occurs set() (instance deprecation warning caught, see #191). with_ local_ functions now robust early exits (see next bullet): _locale() _envvar() _libpaths() _options() _par() _path() _seed() with_namespace() local_namespace() now pass warn.conflicts attach() (@kyleam, #185). local_rng_version() local_seed() longer warn restoring sample.kind \"Rounding\" (#167). with_seed() now preserves current values RNGkind() (#167). with_collate() longer affected LC_COLLATE environment variable set “C” (#179). Local evaluations globalenv() (opposed top-level ones) now unwound way regular environments. local_tempfile() gains lines argument , desired, can pre-fill temporary file data.","code":"old <- get() on.exit(set(old)) set(new) action() old <- set(new) on.exit(set(old)) action()"},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-243","dir":"Changelog","previous_headings":"","what":"withr 2.4.3","title":"withr 2.4.3","text":"CRAN release: 2021-11-30 Lionel Henry new maintainer. Handlers registered global environment (happens local_() run top-level, outside function) now automatically run R session ends (#173). New with_language() local_language() temporarily control language used translations (#180). with_seed() now caches check R version, now faster (#170) with_makevars() local_makevars() now eagerly evaluate path argument (#169)","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-242","dir":"Changelog","previous_headings":"","what":"withr 2.4.2","title":"withr 2.4.2","text":"CRAN release: 2021-04-18 local_options() now lets set option NULL intended (#156) local_tempfile() argument envir deprecated, favor .local_envir. withr functions except local_tempfile() used .local_envir specify environments, makes function consistent rest. (#157) with_environment() now passing pos warn.conflicts attach(), intended (#161). with_seed() now also sets RNG via new arguments .rng_kind, .rng_normal_kind .rng_sample_kind (#162, @AshesITR). with_timezone() now works recent changes Sys.timezone() R-devel (#165)","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-241","dir":"Changelog","previous_headings":"","what":"withr 2.4.1","title":"withr 2.4.1","text":"CRAN release: 2021-01-26 Tests require capabilities(\"cairo\") now skipped.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-240","dir":"Changelog","previous_headings":"","what":"withr 2.4.0","title":"withr 2.4.0","text":"CRAN release: 2021-01-16 withr now licensed MIT (#154). Tests with_cairo_pdf() with_cairo_ps() removed, fail Cairo available, M1 macOS systems (#158) local_seed() now exported (#153)","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-230","dir":"Changelog","previous_headings":"","what":"withr 2.3.0","title":"withr 2.3.0","text":"CRAN release: 2020-09-22","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"deprecations-2-3-0","dir":"Changelog","previous_headings":"","what":"Deprecations","title":"withr 2.3.0","text":"local_tempfile() argument new deprecated, favor returning path new tempfile. calls like local_tempfile(\"xyz\") replaced xyx <- local_tempfile() code (#141).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"new-features-2-3-0","dir":"Changelog","previous_headings":"","what":"New features","title":"withr 2.3.0","text":"New local_seed() function local_preserve_seed() functions correspond with_seed() with_preserve_seed() (#139). New local_tempdir() function added create temp directory (#140) local_*() functions now take dots (...), can simplify calls cases, e.g. can now use local_options(foo = \"bar\") rather local_options(c(foo = \"bar\")).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"minor-improvements-and-fixes-2-3-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and fixes","title":"withr 2.3.0","text":"defer() now throws error error occurs deferred expression (#148) with_file() local_file() can now work file actually directory (#144).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-220","dir":"Changelog","previous_headings":"","what":"withr 2.2.0","title":"withr 2.2.0","text":"CRAN release: 2020-04-20 defer() can set deferred events .GlobalEnv facilitate interactive development code inside function test. Helpers deferred_run() (deferred_clear()) provide way explicity run clear (just clear) deferred events (#76, @jennybc). with_connection() now works existing objects connections exist names (#120) with_makevars() now uses tools::makevars_user() determine default user makevars file (#77, @siddharthab). with_options() longer uses .call(), optiosn evaluated exit (#73, @mtmorgan). with_package() longer help argument (#94, @wendtke). with_package() now try detach package already attached calling with_package() (#107) with_preserve_seed() now restores .Random.seed set originally (#124). Add with_rng_version() local_rng_version() functions change version RNG (#90, @gaborcsardi). with_svg() documentation now consistent across R versions (#129) Add with_timezone() local_timezone() functions change time zone (#92, @gaborcsardi). with_tempfile() local_tempfile() now delete recursively directories exit (#84, @meta00).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-212","dir":"Changelog","previous_headings":"","what":"withr 2.1.2","title":"withr 2.1.2","text":"CRAN release: 2018-03-15 set_makevars() now exported (#68, @gaborcsardi). with_temp_libpaths() gains action argument, specify temporary library path added (#66, @krlmlr).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-211","dir":"Changelog","previous_headings":"","what":"withr 2.1.1","title":"withr 2.1.1","text":"CRAN release: 2017-12-19 Fixes test failures testthat 2.0.0 with_file() function automatically remove files.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-210","dir":"Changelog","previous_headings":"","what":"withr 2.1.0","title":"withr 2.1.0","text":"CRAN release: 2017-11-01 with_connection() function automatically close R file connections. with_db_connection() function automatically disconnect DBI database connections. with_gctorture2 command run code gctorture2, useful testing (#47). with_package(), with_namespace() with_environment() (equivalent locals) functions added, run code modified object search path (#38, #48). Add with_tempfile() local_tempfile() functions create temporary files cleanup afterwards. (#32) Remove code argument local_ functions (#50).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-200","dir":"Changelog","previous_headings":"","what":"withr 2.0.0","title":"withr 2.0.0","text":"CRAN release: 2017-07-28 with_ function now local_ variant, reset end local scope, generally end function body. New functions with_seed() with_preserve_seed() running code given random seed (#45, @krlmlr).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-102","dir":"Changelog","previous_headings":"","what":"withr 1.0.2","title":"withr 1.0.2","text":"CRAN release: 2016-06-20 with_makevars() gains assignment argument allow specifying additional assignment types.","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-101","dir":"Changelog","previous_headings":"","what":"withr 1.0.1","title":"withr 1.0.1","text":"CRAN release: 2016-02-04 Relaxed R version requirement 3.0.2 (#35, #39). New with_output_sink() with_message_sink() (#24).","code":""},{"path":"https://withr.r-lib.org/news/index.html","id":"withr-100","dir":"Changelog","previous_headings":"","what":"withr 1.0.0","title":"withr 1.0.0","text":"CRAN release: 2015-09-23 First Public Release","code":""}]