How to Source a Script in R
When you want to tell R to perform several commands one after the other without waiting for additional instructions, you use the source() function. R users refer to this process as sourcing a script.
To prepare your script to be sourced, you first write the entire script in an editor window. In RStudio, for example, the editor window is in the top-left corner of the screen. Whenever you press Enter in the editor window, the cursor moves to the next line, as in any text editor.
Type the following lines of code in the editor window. (Remember that in RStudio the source editor is in the top-left corner, by default.) Notice that the last line contains a small addition to the code you saw earlier: the print() function.
h <- "Hello" yourname <- readline("What is your name?") print(paste(h, yourname))
Remember to type the print() function as part of your script. Sourced scripts behave differently from interactive code in printing results. In interactive mode, a result is printed even without a print() function. But when you source a script, output is printed only if you have an explicit print() function.
You can type multiple lines of code into the source editor without having each line evaluated by R. Then, when you’re ready, you can send the instructions to R — in other words, source the script.
When you use RGui or RStudio, you can do this in one of three ways:
Send an individual line of code from the editor to the console. Click the line of code you want to run, and then press Ctrl+R in RGui. In RStudio, you can press Ctrl+Enter or click the Run button.
Send a block of highlighted code to the console. Select the block of code you want to run, and then press Ctrl+R (in RGui) or Ctrl+Enter (in RStudio).
Send the entire script to the console (which is called sourcing a script). In RGui, click anywhere in your script window, and then choose Edit→Run all. In RStudio, click anywhere in the source editor and press Ctrl+Shift+Enter. Alternatively, you can click the Source button.
These keyboard shortcuts are defined only in RStudio. If you use a different source editor, you may not have the same options.
Now you can send the entire script to the R console. To do this, click the Source button in the top-right corner of the editor window or choose Edit→Source. The script starts, reaches the point where it asks for input, and then waits for you to enter your name in the console window. Notice that the Workspace window now lists the two objects you created: h and yourname.
When you click the Source button, source(‘~/.active-rstudio-document’) appears in the console. What RStudio actually does here is save your script in a temporary file and then use the R function source() to call that script in the console. Remember this function; you’ll meet it again.