Like Excel, R can read in files and create new files based on your commands.
R will assume these files will be read from and written to your directory.
This is a common stumbling block for new R users, but pretty easy to understand with a couple of basic functions.
In the below example, I created a simple vector and then exported it from R using write.table( ):
Somewhere on my machine, there should be a file called x.txt containing my vector. But where? Getwd( ) will tell me:
Sure enough, I find that file in my Documents folder.
But maybe I want to export my file or read them in from somewhere else? Here is where Setwd( ) becomes so powerful:
Now any files I read and write to R will be assumed in my folder, C:/RIsFun.
2 Important Notes:
1. Let’s say you set your directory to one folder but want to write a file to some other folder. You can “override” your directory by including the whole file path in your write.table function.
2.Your slashes are probably wrong.
As this post is written with Excel users in mind, I will assume you’re using Windows.
In the R language, the “” character is an escape character. So when you use the standard Windows directory format, your code will not run.
To avoid this, you can either use two slashes “\” to spell out your directory, or change all your back slashes to forward slashes “/”. I prefer this method.
Code reproduced below: