The setwd Function in R

Master R

By Guangming Lang Comment

Previously, I wrote an article on how not to use setwd(). Today I discovered a side effect of setwd() that is really cool and useful. It turns out that when you run setwd(path), not only will it reset the working directory to path, it will also return the working directory before the reset.

# get the default (current) working directory
getwd()
## [1] "/Users/gmlang/Communities/masterr/_knitr"
# store it
home.path = getwd()

# create a subfolder called Projects
dir.create(file.path(home.path, "Projects"), showWarnings = FALSE)

# reset the Projects folder as the working directory and store the previous working directory in a variable called old  
old = setwd(file.path(home.path, "Projects"))
print(old)
## [1] "/Users/gmlang/Communities/masterr/_knitr"
# check old and home.path are the same
old == home.path
## [1] TRUE
# get the current working directory (this is after the reset)
getwd()
## [1] "/Users/gmlang/Communities/masterr/_knitr/Projects"

We can use this side effect and on.exit()1 to write functions that guaranttees to restore the working directory when the function exists. For example, the following function is taken from Hadley’s book Advanced R.

in_dir = function(dir, code) {
  old = setwd(dir)
  on.exit(setwd(old))

  force(code)
}

Pass the variable old and the function getwd() to it, and you get

in_dir(old, getwd())
## [1] "/Users/gmlang/Communities/masterr/_knitr"
getwd()
## [1] "/Users/gmlang/Communities/masterr/_knitr"
  1. The code in on.exit() is run regardless of whether the function does an early return, throws an error, or simply reaches the end of the function body. 

If you enjoyed this post, get updates. It's FREE