top of page
  • Writer's pictureEkta Aggarwal

Setting working directory in R - setwd getwd

In this tutorial we will understand what is a working directory and how to change it using setwd and getwd



What is a working directory in R?


A working directory is a location where the datasets / files will be read in R. Similarly, all the files will be saved in the location which is specified as you working directory, unless you specify the path yourself.


For eg. Let us say my working directory is : "C:/Users/user/Documents" and it has a file 'mtcars.csv' . Thus R would be able to read this file without specifying this path. i.e.,

To read the file I do not need to write the full path as :

read.csv("C:/Users/user/Documents/mtcars.csv")

I can, in short, use

read.csv("mtcars.csv")

and R will be able to read the files in this directory.



Similarly, if I will write

write.csv(mtcars,"mydata.csv")

then I can see a file mydata.csv created in the current working directory.



How to find my current working directory in R?


Using getwd( ) function, one would be able to see the current working directory in R.


My current working directory is:

getwd()

Output: "C:/Users/user/Documents"



How to change the working directory in R?


There are 2 ways of changing the working directory.


Method 1: Using setwd( ) function


You can use setwd( ) function and specify the file path inside the brackets ( ) within quotes.

Note: In the working directory, by default, file path comprise of "\". Make sure you are using \\ or / in the file path.


Example: Suppose I want to change my directory to: C:\Users\user\Desktop\R. Thus, I can copy my path and











Then I can either use:

setwd("C:\\Users\\user\\Desktop\\R")

or

setwd("C:/Users/user/Desktop/R")

Make sure to replace "\" by either \\ or / in the file path


Method 2: Using simple clicks


You can simply click on Session → Set Working Directory → Choose Directory → And then select your desired location.


Now if you use getwd( ) then it will reflect your new working directory.

getwd()

bottom of page