Skip to content

Instantly share code, notes, and snippets.

@MyKo101
Created July 6, 2021 11:04
Show Gist options
  • Select an option

  • Save MyKo101/02a0aaa509dd1e915c9636d5ceccd967 to your computer and use it in GitHub Desktop.

Select an option

Save MyKo101/02a0aaa509dd1e915c9636d5ceccd967 to your computer and use it in GitHub Desktop.
Apply on.exit() to any environment, useful for parent frames
#' 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