R: Set working directory

How to set work directory in R studio ?

In this article we are going to discuss about how we can set work directory R and also we will verify if that directory has been set perfectly or not. So, let’s start exploring the topic.

R is an interpreted programming language which is created by Ross Ihaka and Robert Gentleman. This programming language and open source environment is used for statistical computing, graphical presentation, data analytics and scientific research.

R studio is an  Integrated Development Environment (IDE) which provides free and open source tools for Rn language.

When working with R language sometimes we need to work with external files and for that we have to set that file directory as working directory otherwise the file won’t be accessible.

So, let’s see how we can set a directory as an working directory in R studio.

Setting up a Working Directory in R studio :

Steps to set working directory in R studio.

  1. Go to session menu.
  2. Select set working directory.
  3. Then select Choose Directory.
  4. From there browse the directory.

Set up Working Directory in R using setwd() function :

By using setwd() function we can set the working directory.

Syntax : setwd("D:/R_workingfile")

For example, we have a directory /Users/BtechGeeks and we want to set it as  working directory then we can do it like this

# command to set working directory.
setwd("Users/BtechGeeks")

If the path does not exist :

If you want to set a directory as working directory but that directory does not exist then it will give Error.

For example, a directory /Users/Btech which does not exists but we want to make it working directory.

Then

# Directory does not exist
setwd("/Users/Btech")
# Raising error as directory does not exit
Error in setwd("/Users/Btech") : cannot change working directory

Verifying the current working directory is set in R :

We can use getwd() function to check the current working directory.

If it returns the correct directory then the working directory has been set perfectly.

# It will give the current working directory
getwd()
>> "/Users/BtechGeeks"