4.6 Saving code in an R script
It might seem like you could just as easily calculate the percentage of vaccinated Marylanders by hand. But what if you had to do it again and again, multiple times a day, for days on end? What if you had to make sure multiple people on your team could perform the same task?
This is where the real strength of R as a programming language comes in. You can save all the steps of your analysis to a script. This is especially powerful if you have long and complicated analyses. It is how R contributes to reproducible and open science.
Open the file vax_count.R. Here we have recorded the steps we just took. So let’s say you were training a new employee to run this very important analysis. Now all they have to do is input the new vaccination number, and run the script.
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).
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.6.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() # 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.
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.