4.2 Scripts

You can create a record of the commands you have executed in the console, but this isn’t a very efficient way to work. If you want to keep track of the commands you’re running (and often you do) its best to write them in a script file and then send them over to the console to execute the code.

4.2.1 Creating scripts

When you open RStudio a blank script file will be open. Subsequently, RStudio will open files you have worked with previously. To create a new blank script file:

  • Click on File
  • New File
  • R script

or just type control + shift + N (on a PC) or command + shift + N on (?on mac), which is similar how you make a new document in most programs.

Creating a new R script file

Figure 4.1: Creating a new R script file

You can create or open multiple scripts, which RStudio organizes as tabs like in a web browser.
R Script file with comments in RStudio

Figure 4.2: R Script file with comments in RStudio

4.2.2 Running code from a script

To run a code you can either place click to the righ of the line of code and click the “run” button.

Running code using RStudios RUN button.  Note cursor to the right of the code

Figure 4.3: Running code using RStudios RUN button. Note cursor to the right of the code

You can also highlight the code by clicking and dragging over it. This is useful when you have multiple lines of code.
Highlighted code in an RStudio script

Figure 4.4: Highlighted code in an RStudio script

4.2.3 Running code with keyboard shortcuts

Want to look like an R pro? Learn keyboard shortcuts so you don’t have to use the mouse. Both of the above methods work using simple keyboard shortcuts:

  • PCs: Control + Enter
  • Macs: Command + Enter (?)

Another handy shortcut is “Control + 2”, which moves your computer’s cursor from the script editor to the console. (Control + 2 moves it from console to editor)