1

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?

mjktfw
  • 840
  • 6
  • 14

2 Answers2

4

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 ...

Romain Francois
  • 17,432
  • 3
  • 51
  • 77
2

Why not just store your starting directory as a variable when you start and use it to reset your directory:

mydir <- getwd()
# do anything
# change directories
# do more stuff
# change directories
# yadda yadda yadda
setwd(mydir)

Also it sounds like you might want to leverage relative paths:

setwd('./subdir')
# do stuff, then go back:
setwd('../')
Thomas
  • 43,637
  • 12
  • 109
  • 140