# The setwd Function in R

## Master R

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.

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.

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

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.