Setting Up a Working Directory in R

When beginning to work with R code, the first thing that you need to do is setup a working directory. A working directory is a location on on your computer from which R will read and write files to. You can choose any location/folder on your computer where you want to save your code and set that as the working directory.

The following example shows how to set the working directory in R to the folder "C:\r-programming\data" on the C drive in Windows.

# Set the working directory
setwd("C:/r-programming/data")

Note: You need to first create a directory called r-programming and then another directory within it called 'data'. Check that you are able to access this directory "C:/r-programming/data" from Windows Explorer. Once the directory exists, you will be able to use the setwd() command to set that as the working directory.

An example for Mac:

setwd("/Users/User Name/Documents/FOLDER")

Note that you must use the forward slash / or double backslash \\ in R! The Windows format of single backslash will not work.

You can check that your working directory has been correctly set by using the function getwd() as shown below:

> getwd()
[1] "C:/r-programming/data"
>

Once you've set a working directory, you can then further navigate to a subfolder by using the same command. In this example, I have a sub-folder called 'arithmetic' where I some r code.

> getwd()
[1] "C:/r-programming/data"
> setwd("arithmetic")
> getwd()
[1] "C:/r-programming/data/arithmetic"

If you want to move back to the parent directory, you can do it as follows:

> setwd("../")
> getwd()
[1] "C:/r-programming/data"

.. means the parent directory, so it goes one level up there

Once we are in a particular folder you read and write files in that folder from R.

We can type the command dir() to get a list of files in that folder.

> getwd()
[1] "C:/r-programming/data"
> setwd("arithmetic")
> getwd()
[1] "C:/r-programming/data/arithmetic"
> dir()
[1] "arithmetic-examples.r"
>

As you can see we have a file called arithmetic-examples.r in the 'data/arithmetic' folder.

Membership
Learn the skills required to excel in data science and data analytics covering R, Python, machine learning, and AI.
I WANT TO JOIN
JOIN 30,000 DATA PROFESSIONALS

Free Guides - Getting Started with R and Python

Enter your name and email address below and we will email you the guides for R programming and Python.

Saylient AI Logo

Take the Next Step in Your Data Career

Join our membership for lifetime unlimited access to all our data analytics and data science learning content and resources.