4.2 Writing R scripts in an editor
There are certainly many cases where it makes sense to type code directly into the console. For example, to open a help menu for a new function with the ? command, to take a quick look at a dataset with the head()
function, or to do simple calculations like 1+1
, you should type directly into the console. However, the problem with writing all your code in the console is that nothing that you write will be saved. So if you make an error, or want to make a change to some earlier code, you have to type it all over again. Not very efficient. For this (and many more reasons), you should write any important code that you want to save as an R script. An R script is just a bunch of R code in a single file. You can write an R script in any text editor, but you should save it with the .R
suffix to make it clear that it contains R code.
In RStudio, you’ll write your R code in the…wait for it…Source window. To start writing a new R script in RStudio, click File – New File – R Script.
Shortcut! To create a new script in R, you can also use the command–shift–N shortcut on Mac. I don’t know what it is on PC…and I don’t want to know. (It’s Ctrl–Shift–N)
When you open a new script, you’ll see a blank page waiting for you to write as much R code as you’d like. In Figure 4.4, I have a new script called examplescript
with a few random calculations.
You can have several R scripts open in the source window in separate tabs (like I have above).
4.2.1 Send code from source to the console
When you type code into an R script, you’ll notice that, unlike typing code into the Console, nothing happens. In order for R to interpret the code, you need to send it from the Editor to the Console. There are a few ways to do this, here are the three most common ways:
Copy the code from the Editor (or anywhere that has valid R code), and paste it into the Console (using Command–V).
Highlight the code you want to run (with your mouse or by holding Shift), then use the Command–Return shortcut (see Figure 4.6).
Place the cursor on a single line you want to run, then use the Command–Return shortcut to run just that line.
99% of the time, I use method 2, where I highlight the code I want, then use the Command–Return shortcut. However, method 3 is great for trouble-shooting code line-by-line.