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.
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 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 setwd("/Users/Atharv")
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 setwd("/Users/dummy")
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. getwd()
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.