Learn R Online

R setwd() in RStudio

In this article you will learn about setwd() function and how to set the current working directory using setwd in rstudio. You will also learn about getwd() to know about working directory in R.

R is pointed to a specific directory called current working directory in which your R files are saved or if you want to read a file then it should be present in that working directory. Dealing with working directory is part and parcel of R programming. 

Syntax of setwd()

The syntax is simple as this function takes only one argument.

> setwd(path)

where path is a character string which is the directory path of your desired working directory. 

If you are an absolute beginner in R and want to learn R for data analysis or data science from R experts I will strongly suggest you to see this R for Absolute Beginners Course

Example of setwd

Lets suppose you have a folder named myfiles saved in a folder rfiles saved on d drive on windows OS. The path of myfiles will be like 


However, when you define the argument path it should either contain two backslashes or a forward slash in place of \. That means instead of 






Similarly you can set working directory on Linux and Mac with forward slashes.

The reason is that backspace is considered as an escape character in R. Hence either use \\ in place of \ or simply use a forward slash. The first backslash will tell R interpreter that the next backslash is not an escape character or it does not have a special meaning use it simply as character literal.

setwd in RStudio

It is better to use RStudio for R programming, because it will be same environment on all platforms Windows, linux or Mac. If you have to set your working directory in rstudio in addition to the method already explained you may set it by pressing these three keys simultaneously

Control + Shift + h

or go to menubar and click Session menu

Rstudio How to set working directory with setwd()

in dropdown menu click Set working directory and then on right side click the last option choose directory. It will open the dialog box and you can choose the directory.

Session > Set Working Directory > Choose Directory

getwd function

Before setting your working directory you might be interested in to get information about your current working directory and for that getwd() function is used. This function does not take any argument and returns a character string which is the full path of working directory. 


> getwd()

[1] "C:/Users/Programmar/Documents"

Here documents is the default working directory. 

You can notice that the path returned by R uses forward slashes / for directory structure as we have discussed earlier. So better to stick with this style.