4.3 Saving code in an R script

Working in the console in R you can run all the commands necessary to perform a data analysis. However one of the great features of R is that its a programming language. So as you are running the commands to perform an analysis you can also be creating a record of what you have run. Creating a script is a way to do this which can ensure reproducibility.

The usual workflow is to save your code in an R script (“.R file”). Go to “File/New File/R Script” to create a new R script. Code in your R script can be sent to the console by selecting it or placing the cursor on the correct line, and then pressing Control-Enter (Command-Enter on a Mac).

Tip
Add comments to code, using lines starting with the # character. This makes it easier for others to follow what the code is doing (and also for us the next time we come back to it).

4.3.1 Setting your Working Directory

The working directory is the location within which R points to the files system. RStudio sets up a default working directory, typically the home directory of the computer, which can be changed in the global options setting in RStudio.

In the code samples provided the data files are located in the R working directory, which can be found with the function getwd.

getwd() # get current working directory

You can select a different working directory with the function setwd(), and thus avoid entering the full path of the data files.

setwd("<new path>")   # set working directory

Note that the forward slash should be used as the path separator even on Windows platform.

setwd("C:/MyDoc")

Alternatively you can go to the working directory and set the working directory using the files panel and clicking the gear wheel for “more” within RStudio.

Or by selecting the drop down list found in Tools(Windows) or Session(Mac) in the menu at the top of the RStudio window.