Search code examples
rdirectorysetwd

Convenient directory handling in R


Since I'm working with many subdirectories, I find setwd() pretty inconvient, as it demands from me to remember what are the current and previous location and change them back every time I perform different analysis. Things get more complicated when some paths need to be relative and other absolute. I'm looking for a convenient way to apply the change for the specific fraction of code, as in Ruby:

Dir.chdir("newDir") do
  # some code here #
end

I've written such ugly functions:

path = list()

tempDirNew <- function(..., abs= FALSE){
  path$tempDir$old <<- getwd()
  mod = ifelse(abs == TRUE,
         '',
         path$tempDir$old)
  path$tempDir$new <<- file.path(mod, ...)

  dir.create(path= path$tempDir$new, showWarnings= FALSE)
  setwd(dir= file.path(path$tempDir$new))
}

tempDirOld <- function(){
  setwd(dir= path$tempDir$old)
  path$tempDir$new <- NULL
  path$tempDir$old <- NULL
}

and apply tempDirNew('newdir') before and tempDirOld() after each part of the code. But maybe there is some built-in, convenient way?


Solution

  • You might like that setwd returns the previous directory, so that you can do something like this in your functions:

    f <- function(){
       old <- setwd( "some/where" )
       on.exit( setwd(old) )
    
       # do something
    } 
    

    This way, you don't mess with global variables, <<- etc ...