Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add short vignette on writing your own withr-like functions #217

Open
jennybc opened this issue Mar 16, 2023 · 0 comments
Open

Add short vignette on writing your own withr-like functions #217

jennybc opened this issue Mar 16, 2023 · 0 comments

Comments

@jennybc
Copy link
Member

jennybc commented Mar 16, 2023

I think this technique is known to some, but not to many others and I can't find an existing demo within withr's docs (I could be wrong). But if I'm right, I think this would make a great short vignette.

Basically showing how to capture and pass along the environment that you want to schedule future actions on.

local_change_digits <- function(new_digits, envir = rlang::caller_env()) {
  op <- options(digits = new_digits)
  withr::defer(options(op), envir = envir)
}

fun <- function() {
  print("inside fun, before calling local_change_digits(): ")
  print(pi)
  
  local_change_digits(2)
  
  print("inside fun, after calling local_change_digits(): ")
  print("after: ")
  print(pi)
  
  invisible()
}

pi
#> [1] 3.141593
fun()
#> [1] "inside fun, before calling local_change_digits(): "
#> [1] 3.141593
#> [1] "inside fun, after calling local_change_digits(): "
#> [1] "after: "
#> [1] 3.1
pi
#> [1] 3.141593

Created on 2023-03-16 with reprex v2.0.2.9000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant