Created
July 6, 2021 11:04
-
-
Save MyKo101/02a0aaa509dd1e915c9636d5ceccd967 to your computer and use it in GitHub Desktop.
Apply on.exit() to any environment, useful for parent frames
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #' Apply on.exit() anywhere | |
| #' | |
| #' Apply the on.exit() functionality to any environment | |
| #' | |
| #' Very useful for creating and closing temporary connections (see examples) | |
| #' | |
| #' @examples | |
| #' local_sink <- function(file){ | |
| #' sink(file) | |
| #' on.exit.env(sink(),env=parent.frame()) | |
| #' } | |
| #' | |
| #' f <- function(){ | |
| #' cat("Sinking to console\n") | |
| #' local_sink("temp.txt") | |
| #' cat("Sinking to temp.txt\n") | |
| #' } | |
| #' | |
| #' f() | |
| #' cat("sink has been removed!") | |
| on.exit.env <- function(expr=NULL,add=TRUE,after=TRUE,env=parent.frame()){ | |
| do.call("on.exit", | |
| list(expr=substitute(expr), | |
| add = substitute(add), | |
| after = substitute(after)), | |
| envir=env) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment