R: Set working directory

In this article, we will be setting up a working directory in R using different techniques and will also verify if that has been set correctly.

We ought to know how to do the same because, at times, while working in R, we will have to use some external files, and unless the directory these files are placed in is not set as a working directory, they will not be accessible.

Let’s see how to set any directory as a working directory. We will be looking into two ways.

  1. Using Rstudio
  2. Using R function
  3. Verify that current working directory is set in R

Set up a Working Directory in R studio

If you are using R studio, go to the sessions menu, select Set Working Directory, and then select Choose Directory. From here, we can browse the directory.


See the below figure.

Set current working directory in R studio
Set current working directory in R studio


Set up Working Directory in R using setwd() function

Use the setwd(“arguments”) function, the arguments passed in this function are character string which is the path of the directory For example :


Now, let us try with an example :

Suppose we have a directory /Users/Atharv and we want to set it as our working directory. To accomplish the task type the below code in your workspace.

#code to set working directory

If you are using RStudio your console will show the same command, as setwd() does not return anything but will set up the directory you have passed as an argument in setwd() function.

What if the path does not exist?

In case the folder you passed in the setwd() function does not exists, then below error will be shown in the console :

#code to set working directory
Error in setwd("/Users/Atharv") : cannot change working directory

How to verify that current working directory is set in R

R provides a function getwd(), which returns the current working directory as character string. Let’s use this to verify if setwd() has done its job correctly,

#get the absolute filepath of the current working directory of the R process.




Tip: Please be cautious while changing the working directory, as when you change your previous working directory then, the relative files you are using will become invalid, which may contain your datasets or other important stuff.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top