Skip to content

Instantly share code, notes, and snippets.

@turgeonmaxime
Created November 23, 2015 18:27
Show Gist options
  • Save turgeonmaxime/b768e03f34e47b8d1662 to your computer and use it in GitHub Desktop.
Save turgeonmaxime/b768e03f34e47b8d1662 to your computer and use it in GitHub Desktop.
setwd which allows for path containing Unix-like environment variables
#' Set Working Directory
#'
#' \code{setwd(dir)} is used to set the working directory to \code{dir}.
#'
#' This version of \code{setwd} is different from the one in \code{base} in that it allows for paths containing Unix-like
#' environment variables. For example, if HOME is set (globally) to your home directory, then \code{base::setwd($HOME)}
#' will not work. However, the version below will work.
#'
#' @param dir A character string: tilde expansion will be done.
setwd <- function(dir) {
if (!grepl("$", dir, fixed = TRUE)) {
# If there is no environment variable, use the usual setwd function
base::setwd(dir)
} else {
# Separate dir into its components, those separated by /
comp <- strsplit(path.expand(dir), split = "/", fixed = TRUE)[[1]]
# Focus only on those containing a $
var <- comp[grep("$", comp, fixed = TRUE)]
# Retrieve value for variables; need to remove $ before the call
var <- Sys.getenv(substr(var, start = 2, stop = nchar(var)))
# Substitute results in place of original variable
comp[grep("$", comp, fixed = TRUE)] <- var
base::setwd(paste(comp, collapse = "/"))
}
}
@turgeonmaxime
Copy link
Author

There may be some problems left with the above code. For example, this may fail in a non-obvious way on Windows and non Unix-like machines. Moreover, it implicitly assumes (on line 21) that the dollar sign $ appears at the beginning of the string (is there a realistic scenario where this could cause some problems?).

I'm open to suggestions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment