When beginning to work with R code, the first thing that you need to do is setup a working directory. A working directory is a location on on your computer from which R will read and write files to. You can choose any location/folder on your computer where you want to save your code and set that as the working directory.
The following example shows how to set the working directory in R to the folder
"C:\r-programming\data" on the C drive in Windows.
# Set the working directory setwd("C:/r-programming/data")
Note: You need to first create a directory called r-programming and then another directory within it called ‘data’. Check that you are able to access this directory “C:/r-programming/data” from Windows Explorer. Once the directory exists, you will be able to use the setwd() command to set that as the working directory.
An example for Mac:
Note that you must use the forward slash / or double backslash \\ in R! The Windows format of single backslash will not work.
You can check that your working directory has been correctly set by using the function
getwd() as shown below:
> getwd()  "C:/r-programming/data" >
Once you’ve set a working directory, you can then further navigate to a subfolder by using the same command. In this example, I have a sub-folder called ‘arithmetic’ where I some r code.
> getwd()  "C:/r-programming/data" > setwd("arithmetic") > getwd()  "C:/r-programming/data/arithmetic"
If you want to move back to the parent directory, you can do it as follows:
> setwd("../") > getwd()  "C:/r-programming/data"
.. means the parent directory, so it goes one level up there
Once we are in a particular folder you read and write files in that folder from R.
We can type the command
dir() to get a list of files in that folder.
> getwd()  "C:/r-programming/data" > setwd("arithmetic") > getwd()  "C:/r-programming/data/arithmetic" > dir()  "arithmetic-examples.r" >
As you can see we have a file called
arithmetic-examples.r in the