What is the setwd() Function in R

The setwd() function in R is “used to set the working directory to the new location”. The working directory is the location where R looks for files when you try to read or write them. You can use the getwd() function to get the current working directory.




The function takes dir as an argument, and a character string: tilde expansion will be done.

Return Value

The setwd() method returns the current directory before the change, invisibly and with the same conventions as the getwd() function. It will give an error if it does not succeed.


The setwd() function requires the new working directory as an argument to the function.


In this example, we had to specify a character string containing the filepath we want to use within the setwd function. This is because you have to use a slash (not a backslash) to specify your path when working on a Windows computer.

How to set the current working directory in RStudio

To set the current working directory in RStudio,

  1. Create a sub-directory, say R, in your “Documents” folder. This sub-folder, also known as a working directory, will be used by R to read and save files.
  2. Launch R by double-clicking on the icon.
  3. Specify your working directory to R:
    • On Windows: File –> Change directory
    • On MAC OSX: Tools –> Change the working directory

The getwd() in R is a built-in function that returns the absolute filepath representing the current working directory of the R process.

A working directory can be your best friend or ruthless adversary. Confusion about the working directory is a great time waster. You must ensure you are in the correct directory to perform advanced action. Otherwise, it can create an issue for you.

Leave a Comment