How to Set and Get Working Directory [setwd() and getwd()] in R

Set the current working directory

The setwd() function is used to set the working directory to the new location. Provide the path to the desired directory as an argument to this function.

Syntax

setwd(dir)

Parameters

dir: Replace “dir” with the actual path where you want to set your working directory. The path can be relative to the current directory or an absolute path.

Platform-specific path

The format of the file path depends on your operating system.

Windows paths use backslashes (\), while Unix-like systems (including macOS and Linux) use forward slashes (/). In R, you can use forward slashes on Windows as well.

If you are using Windows and prefer to use backslashes, remember to escape them (\\) or use raw strings (e.g., r”(C:\Your\Path)”).

Using relative paths in this function can be helpful, especially when sharing code with others, but be mindful of the current working directory before the change, as it affects the interpretation of the relative path.

Example

# Set the working directory to a new location
setwd("/Users/krunallathiya/Desktop/Code/pythonenv/env")

# Verify the change
new_directory <- getwd()

print(new_directory)

Output

[1] "/Users/krunallathiya/Desktop/Code/pythonenv/env"

Set the Current Working Directory in RStudio

To set the current working directory in RStudio, use the menu to change your working directory under Session > Set Working Directory > Choose Directory.

Figure 1 - Choosing a directory

Set a Default Working Directory Globally in RStudio

You can set the default working directory from the RStudio menu under Tools –> Global options –> click “Browse” to select your desired default working directory.

Step 1: Go to the tools and select the Global options

Check out the screenshot below. I am using the RStudio version “2021.09.0+351”, the latest version in 2023.

Screenshot of navigating to the tools and select the Global options

Step 2: Select the directory you want to set as a default

Set the current working directory in R
Figure 3: Select a directory to set the default working directory

It will set the working directory globally in RStudio.

Get the current working directory

The getwd() function is used to get the current working directory. It does not take any parameters and returns the absolute filepath.

Syntax

getwd()

Parameters

It does not take any parameters.

Return value

It returns a character string or NULL if the working directory is unavailable.

On Windows OS, the path returned will use “/” as the path separator and be encoded in UTF-8. The path will not have a trailing / unless it is the root directory.

Example

Write the following single line of code in the R file and run it in the RStudio console.

getwd()

Output

Output of current working directory in R
Figure 4: Usage of getwd() function

That’s it!

Leave a Comment