Skip to content

Commit

Permalink
Add the 'with_wd' function originally written by Tyler Smith, with an…
Browse files Browse the repository at this point in the history
… example added by Leo to form a complete unit at https://github.com/LieberInstitute/sgejobs/blob/devel/R/utils.R

Co-authored-by: Leonardo Collado Torres <[email protected]>
  • Loading branch information
Nick-Eagles and lcolladotor committed Sep 29, 2023
1 parent 7a2a821 commit bc56202
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#' Temporarily evaluate an expression in a directory
#'
#' Temporarily evaluate an expression in a directory, then set the directory
#' back to the original.
#'
#' @param dir a directory to perform an expression within.
#' @param expr expression to evaluate.
#'
#' @details See here: http://plantarum.ca/code/setwd-part2/
#' @export
#' @author Tyler Smith, contributed to regionReport by David Robinson
#' https://github.com/dgrtwo
#'
#' @examples
#'
#' ## Create a directory called 'hola' and then check that it exists
#' with_wd(tempdir(), {
#' dir.create("hola", showWarnings = FALSE)
#' file.exists("hola")
#' })
#'
with_wd <- function(dir, expr) {
wd <- getwd()
on.exit(setwd(wd))
setwd(dir)
eval(expr, envir = parent.frame())
}

0 comments on commit bc56202

Please sign in to comment.