R Advanced

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

Set the current working directory

The setwd() function sets the working directory to the new location, allowing us to change the default location for file operations.

The working directory is a location where R looks for files to read or save by default.

Use absolute paths for reliability, relative paths for flexibility.

Syntax

setwd(dir)

Parameters

Argument Description
dir It represents a character string specifying the new working directory 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.

# Windows - use forward slashes or double backslashes

setwd("C:/Users/krunallathiya/Desktop/Code/pythonenv/env")

setwd("C:\\Users\\krunallathiya\\Desktop\\Code\\pythonenv\\env")

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

Unix/Linux/Mac paths

# Unix-like systems

setwd("/home/krunallathiya/Desktop/Code/pythonenv/env")

setwd("~/Documents")

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

# Setting 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.

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.

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

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

What if the directory doesn’t exist?

What if your directory does not exist, and you are trying to set that directory? In that case, you will face the error, and the program will crash. But how to prevent that?

Well, that’s where the tryCatch() function comes into play. It will handle the error and will not crash your program.

tryCatch(
 {
   setwd("/nonexistent/directory")
 },
 error = function(e) {
   cat("Error:", e$message, "\n")
 }
)

# Output: Error: cannot change working directory

Safe directory setting

It is not an easy task to safely set a directory, but with the help of a proper file handling function, you can achieve it.

First, we will use the dir.exists(path) method to check if that directory already exists. If not, we won’t proceed and will return from the program. However, if it exists, we use the tryCatch() function to attempt to change the directory to the current working directory.

If the operation is successful, we print the message saying “Successfully changed to your current working directory”. If the operation fails, we print the error and then debug it to fix the error.

safe_setwd <- function(path) {
  if (!dir.exists(path)) {
    cat("Directory does not exist:", path, "\n")
    return(FALSE)
  }

 tryCatch(
 {
   setwd(path)
   cat("Successfully changed to:", getwd(), "\n")
   return(TRUE)
 },
 error = function(e) {
   cat("Failed to change directory:", e$message, "\n")
   return(FALSE)
  }
 )
}

safe_setwd("/path/to/project")

# Successfully changed to: /path/to/project

If you have any error, it will print the following output:

Directory does not exist: /path/to/project

[1] FALSE

Use on.exit() or tryCatch() to ensure directory restoration after errors.

That’s it!

Recent Posts

Standard deviation in R [Using sd() Function]

The sd() function in R calculates the sample standard deviation of a numeric vector or…

3 days ago

R dnorm(): Probability Density Function

The dnorm() function in R calculates the value of the probability density function (pdf) of…

4 days ago

R rep() Function: Repeating Elements of a Vector

R rep() is a generic function that replicates elements of vectors and lists for a…

1 week ago

Splitting Strings: A Beginner’s Guide to strsplit() in R

The strsplit() function in R splits elements of a character vector into a list of…

1 week ago

Understanding of rnorm() Function in R

The rnorm() method in R generates random numbers from a normal (Gaussian) distribution, which is…

2 weeks ago

as.factor() in R: Converting a Vector to Categorical Data

The as.factor() function in R converts a vector object into a factor. Factors store unique…

2 weeks ago