3.4 The Scripting Workflow

But hold on, we’re still not quite ready to start coding. As mentioned above, all important R code should be written and saved in a file before you run it! Your scripts will very quickly contain many lines of code that are meant to be run in sequential order. While developing your code it is very helpful to run each individual line separately, building up your script incrementally over time. To illustrate how to do this, we will begin with a simple R code that stores the result of an arithmetic expression to a new variable:

# stores the result of 1+1 into a variable named 'a'
a <- 1+1

The concepts in this line of code will be covered in greater depth later, but for now an intuitive understanding will suffice to explain the development workflow in RStudio.

When developing, this is the suggested sequence of operations:

  1. Save your file (naming if necessary on the first save) with Ctrl-s on Windows or Cmd-s on Mac
  2. Execute the line or lines of code in your script you wish to evaluate using Ctrl-Enter on Windows or Cmd-Enter on Mac. By default only the line with the cursor is executed; you may click and drag with the mouse to select multiple lines to execute if needed. NB: you can press the up arrow key to recall previously run commands on the console.
  3. The executed code will be evaluated in the Console window, where you may inspect the result and modify the code if necessary.
  4. You may inspect the definitions of any variables you have declared in the Environment tab at the upper right.
  5. When you have verified that the code you executed does what you intend, ensure the code in the file you started from is updated appropriately.
  6. Go to step 1

The above steps are depicted in the following figure:

RStudio workflow

Over time, you will gain comfort with this workflow and become more flexible with how you use RStudio.

If you followed the instructions above and prevented RStudio from saving your environment when you exit the program (which you should! Did I mention you should?!), none of the results of code you previously ran will be available upon starting a new RStudio session. Although this may seem inconvenient, this is an excellent opportunity to verify that your script in its current state does what you intend for it to do.

It is extremely easy to ask R to do things you don’t mean for it to do!

Rerunning your scripts from the beginning in a new RStudio session is an excellent way to guard against this kind of error. This short page summarizes this very well, you should read it: