Chapter 3 R-Scripts
As your analysis conducted in R gets more complicated (at least in the number of expressions to evaluate), you may want to save your work as an R script, rather than typing one command after the other into the console. An R Script is really just a plain text file containing R code that can be executed. A major benefit of R scripts is that you preserve the analysis you did and can easily re-run it again - that is not only going to save you time, but it will also make your work reproducible.
RStudio is fantastic for working with R scripts. Just click on File -> New File -> R Script in the menu and a new file will be opened in the source pane. There, you can type your R code and save it for later use, but also send it to the console for execution.
For instance, copy the following code into an empty R script:
You can now execute this R-script in one of two ways in RStudio:
You can send line by line to the console. for this, place the cursor anywhere on the chosen line an click the “Run” button (or press
Ctrl
+Enter
as a shortcut). The cursor will automatically jump to the next line, so you can just keep pressing the “Run” button (or pressingCtrl
+Enter
) until you reach the end of the script.Alternatively, you can ask for the whole document to be executed. For this, simply press the “Source” button (or press
Ctrl
+Shift
+Enter
as a shortcut).
Cool, no?
3.0.1 Exercises: R-Scripts
See Section 18.0.4 for solutions.
Create an R-script that assigns the values , 10 and to variables
my_data
,base_1
andbase_2
and then prints the log ofmy_data
with both bases. Use comments to explain your script and save it asmyFirstRScript.r
on your computer.Execute your script
myFirstRScript.r
both line-by-line as well as in one go (i.e. source it).
Comments
As your R code will grow, it will become very important to comment it properly. Indeed, a variable
day_1
will maybe mean a a lot to you while writing your code, but will you remember its meaning when going back to it after one year? Similarly, you maybe side with a particular statistical analysis, but will you remember the reasoning a year later?Most peopel don’t - which is why most people should add comments to their code. In R, comments always start with a
#
symbol. This tells R that everything after the#
is not R code and is to be ignored.You can add comments at the end of a line too
Since R scripts can get very long, you can also use comments to structure them or leave other worthy notes. Here is an example: