Working directories and relative paths in R

R gives the possibility to the reader to set the so called working directory, which is analogous to the current directory, typical of  command-line tools. This working directory has to be intended as the folder where we are going to store the greatest part, if not all the files,. needed for our current analysis. Technically this will result in a different behavior from the interpreter when facing a file path.

To understand how this works, we can try the following experiment, starting from our desktop let us create a subfolder, named analysis_directory so that the path of this directory from the desktop will look as follows:

/Desktop/analysis_directory

We now place a new text file into the subfolder analysis_directory, namely experiment.csv. Finally, we go to the R console and request to the console to show the current the working directory, as follows: getwd().

This results in the console printing out the absolute path leading to the current working directory. We now try to set it to the desktop folder, running a command like the following: setwd("/Users/andrea_cirillo/Desktop").

If you are working in a Windows OS, just look for the address bar into your file system explorer and you will find the full path to your desktop folder. Now that we have set our working directory to the desktop, we can try, for instance, to import the file experiment.csv. Let us try in the most naive way and see what happens: import(experiment.csv).

Unfortunately we will be prompted with an error message similar to the following: Error in import("experiment.csv") : No such file.

 Why? Because R made the following reasoning: He is asking me to look for the file experiment.csv, but where to find it? I am going to look for it within my working directory... oh,no! There is no such file here!

May be this was a bit too much colored version of the reality, nevertheless it gets the point: R define the path where to look for the file attaching to the file name the absolute path from the computer root to the working directory. Within our example it will therefore look at the following path:
/Users/andrea_cirillo/Desktop/experiment.csv.

What is missing here? The analysis_directory folder, we have to submit the relative path from the working directory to our file. This is easily done with a slightly modified version of the previous code: import("analysis_directory/experiment.csv")

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset