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.
1# Set the working directory
2setwd("C:/r-programming/data")
3
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:
setwd("/Users/User Name/Documents/FOLDER")
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:
1> getwd()
2[1] "C:/r-programming/data"
3>
4
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
for some R code.
1> getwd()
2[1] "C:/r-programming/data"
3> setwd("arithmetic")
4> getwd()
5[1] "C:/r-programming/data/arithmetic"
6
If you want to move back to the parent directory, you can do it as follows:
1> setwd("../")
2> getwd()
3[1] "C:/r-programming/data"
4
..
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.
1> getwd()
2[1] "C:/r-programming/data"
3> setwd("arithmetic")
4> getwd()
5[1] "C:/r-programming/data/arithmetic"
6> dir()
7[1] "arithmetic-examples.r"
8>
9
As you can see we have a file called arithmetic-examples.r
in the 'data/arithmetic'
folder.