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.
The syntax is simple as this function takes only one argument.
where path is a character string which is the directory path of your desired working directory.
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.
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
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
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.
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.