2.3 Writing R scripts

As mentioned in Section 2.2.2, R Scripts are the primary method for building an analysis. They are text files storing the recipe or set of R commands to complete the analysis. There are several ways to create a new R Script:

  • Click the the icon near the upper left that looks like a piece of paper with a green plus on it
  • Click on the menu File -> New File -> R Script
  • Use the keyboard shortcut Ctrl + Shift + N

You can also open existing files using File -> Open or Ctrl + O. To help get your feet wet, create a new R Script and type the following lines:

  x <- rnorm(n = 1000, mean = 10, sd = 4)
  mean(x)
## [1] 10.04155

Execute a command from your script by first clicking within the line with your mouse and then clicking the Run button or using the keyboard shortcut Ctrl + Enter. To execute multiple lines at once, click and drag your mouse to select the desired lines before clicking the the Run button or using the keyboard shortcut. You can execute the entire script by clicking on the Source button or using the keyboard shortcut Ctrl + Shift + S.

Try executing the lines above. Compare your output. It’s probably very close but not exactly the same! No worries—the first line creates a random normal distribution.

2.3.1 Commenting with #

The source pane allows you to annotate your code with “comments,” helping you to keep your work organized and comprehensible. Comments can function as section headers, or as notes to your future self/colleagues on what you were attempting to do. R treats anything after the # sign as a comment and ignores it when executing commands. For instance:

# Practice executing commands    
  x <- rnorm(n = 1000, mean = 10, sd = 4)  # create a new object, x
  mean(x)                                 # calculate the mean of it
## [1] 9.845282

2.3.2 Saving your R Script

R Scripts embody a complete, precise record of every step involved in a particular analysis, which offers two big benefits. First, you can return to an analysis to expand on it or correct errors. Second, you can easily share it with others, who will then be able to understand exactly what you did and reproduce your work.

But you must save your R Script to get these these benefits. Make sure to do so regularly by:

  • Clicking the floppy disk icon
  • Clicking on the menu File -> Save (or File -> Save As)
  • Using the keyboard shortcut Ctrl + S

The first time you save an R Script, you will be prompted to select a destination directory and a file name. You can choose any convenient directory for your R Script. For example, you do not need to save the R Script in the same directory as other files, e.g. source data, used in your analysis.

As we will see in Section 2.5, there is a R command that allows us to specify which directory stores source data or other relevant files independent of the location of your R Script file.