mjktfw
mjktfw

Reputation: 870

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?

Upvotes: 1

Views: 236

Answers (2)

Thomas
Thomas

Reputation: 44525

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('../')

Upvotes: 2

Romain Francois
Romain Francois

Reputation: 17642

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

Upvotes: 4

Related Questions