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.
Syntax
setwd(dir)
Parameters
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.
Example
The setwd() function requires the new working directory as an argument to the function.
ls()
character(0)
getwd()
setwd("/Users/krunal/Desktop/code/R/data")
setwd("packageFiles")
getwd()
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,
- 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.
- Launch R by double-clicking on the icon.
- 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.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.