setwd / getwd – Setting The Working Directory In R

Like many desktop applications, your R environment is always pointed at a specific directory on your computer. This directory is commonly referred to as the working directory.

The working directory can be your best friend or ruthless foe. Confusion about the working directory is a great time waster. I’ve had this happen with data files or code modules. The other game it plays is “where did we save that chart”. Like looking for a¬†saved graphic?

Of course it isn’t all bad. Automation rocks. I love automating data loads by sweeping a directory. Or even better, scripts that trigger other scripts. This can save you hours of time.

getwd – get current working directory


This little function – which requires no arguments – will tell you the working directory. This is useful for debugging. This is also useful for larger programs to iterate through the contents of a directory.

getwd() returns an absolute filepath representing the current working directory. This result will be a character string. It can return Null if the working directory is not available. For users using Windows, the path will use “/” as a separator between levels of the directory. The path will not have a trailing slash unless it is the root directory.

setwd() – Set or Change R Working Directory


This one is simple enough. To change the current working directory, use the setwd R function. The function requires the new working directory as an argument to the function. You can define this in absolute terms (a specific path). You can also use “..” to navigate up to the parent directory.

If setwd cannot complete the change, it will throw an error.

A Deeper Application of setwd

The typical user uses setwd () to navigate their data directory. This function has uses beyond that, however. The example below allows you to iterate and execute a set of scripts.

  • Setwd is used to point at a particular directory
  • list.files is used to grab everything in the directory and subfolders
  • We pattern match to get the scripts we need
  • Use the source function to execute the R code
# set the working directory your scripts folder
setwd( "/user/you/scriptrepo" )

# pull all files and folders (including subfolders) into a character vector
# keep ONLY the files that END with ".R" or ".r"
scriptlist <- list.files( pattern=".*\\.[rR]$" , recursive = TRUE )

# loop through and trigger scripts using source ()
for ( i in scriptlist ) source( i )

Furthermore, each script is executing within its subfolder. This allows us to load / use different (and potentially conflicting) versions of any supporting scripts and data sets.