R/make_copies.R

Defines functions make_copies

Documented in make_copies

#' Duplicate objects in the global environment based on names matching a grep pattern.
#'
#' Duplicate multiple ojects in an environment based on a grep pattern match. This allows modification of one version of the objects without losing the previous versions. Useful for testing modifications to objects generated by time-consuming code. This is a simple wrapper for makeCopy.
#' @param var_pattern character string, the regex pattern to match object names. Passed to \code{grep} via \code{ls_grep}.
#' @param append character string, the text to be appended to the objects' names when making the copies. Defaults to ".old".
#' @param ask logical, whether to prompt the user before copying objects. Defaults to TRUE.
#' @param envir the name of the environment in which to make the changes. Defaults to the global environment, \code{.GlobalEnv}.
#' @export
#' @usage make_copies(var_pattern, append=".old", ask=TRUE, envir=.GlobalEnv)
make_copies <- function(var_pattern, append=".old", ask=TRUE, envir=.GlobalEnv) {
  vars_to_copy <- ls_grep(var_pattern)
  if (ask) {
    cat("About to copy the following objects with suffix '", append, "':\n\n", sep="")
    cat(vars_to_copy, sep = "\n")
    proceed <- read_yn("Do you want to proceed? (Enter y or n): ")
    if (proceed == "n")
      stop("Variables not replaced.")
  }
  invisible(lapply(vars_to_copy, make_copy, append=append, envir=envir))
}
mjdufort/miscHelpers documentation built on Feb. 4, 2024, 7:44 p.m.