From bc562027006385a81c8c6e5e53b28e2a0482da0b Mon Sep 17 00:00:00 2001 From: Nick-Eagles Date: Fri, 29 Sep 2023 10:11:53 -0400 Subject: [PATCH] Add the 'with_wd' function originally written by Tyler Smith, with an 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 --- R/utils.R | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 R/utils.R diff --git a/R/utils.R b/R/utils.R new file mode 100644 index 0000000..aa75274 --- /dev/null +++ b/R/utils.R @@ -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()) +}