In This chapter we will learn how to Set current working directory in R using setwd() function and also using GUI in Rstudio. We will also take up an example on get current working directory in R using getwd() function.
- Get current working directory in R using getwd() function
- Set working directory using setwd() function
- Set working directory using user interface in Rstudio.
Set working Directory in R:
If you want to read files from a specific location or write files to a specific location, you need to set working directory in R. This can be accomplished by specifying path with in setwd() function. The following example shows how to set the working directory.
# set working directory in R setwd("D:/ LearningR”)
which sets working directory to LearningR folder in D drive.
Get working directory in R:
R will always be pointing to a directory on your computer. You can find out which directory by running the getwd() function. The following example shows how to get the working directory in R
# get current working directory in R getwd()
Output will be current working directory
Set Working directory in RStudio through GUI(Graphical user interface):
Method 1:
In R studio we can set working directory in 3 steps through GUI.
Step 1: on Right side down quadrant, under files tab click … as shown in the red box below
Step 2: It will pop up the navigation box, through which you can navigate to the desired location you want and click ok button
Step 3: now under file tab click More > Set As Working Directory as shown below
Now the working directory will be set. Thus we can set working directory in Rstudio through GUI.
Method 2 : Change your working directory
You can also change your working directory as follow:
- Create a sub-directory named “R” in your “Documents” folder
- From RStudio, use the menu to change your working directory under Session > Set Working Directory > Choose Directory.
- Choose the directory you’ve just created in step 1
which is pictographically shown below