Getting familiar with the working environment: Getting familiar with the R interface
Writing and running an R script
Writing an R script Writing a script in R involves creating a series of R commands and statements that perform specific tasks, analyze data, or solve a problem. You can start writing your R code in the script that you opened in the Source editor panel. You can use the basic R syntax, functions, and packages that you will learn in this course to perform various tasks.
When you start to write a script, it is important that you state what you are working on, who is the author and which version you are working on. Commenting your code in this way will increase its readability and makes your code easy to understand. In a separate style guide page we will give some suggestions
Explanation Be aware that the # symbol in the R script on the right-hand side initiates a comment. It can be used to explain what the R code does or is intended to do. Text in the line after this symbol will not be executed as an instruction. Comments are in general short statements, not necessarily complete sentences. |
R script # Aim: Give an example of how to write and execute a script
|
Running an R script To execute or run a line of code in a script, place your cursor anywhere in that line and click on the Run button at the top of the source editor, or press Ctrl + Enter
(MS Windows) or Cmd + Enter
(macOS). This will execute the selected line of code. If you want to execute multiple lines of code (a block of code), you can highlight the lines you want to run using the mouse or keyboard and then press the keys Ctrl + Enter
(MS Windows) or Cmd + Enter
(macOS) simultaneously. This will execute all of the selected lines of code in the order in which they occur in the script. If you want to execute the whole script at once, click the Source button at the top of the Source editor, or enter the key combination Ctrl + Shift + Enter
(MS Windows) or Cmd + Shift + Enter
(macOS). In this case hardly any output appears in the console panel: only messages (mostly error messages) or something that you deliberately want to output via a print
instruction.
When you run the R script in the example above, your working environment may look like the following screen shot:
If you run lines of code, what you print will be displayed in the Console panel; in this case you get the numbers \(15\) and \(50\). The [1]
before the numbers means that each time only a single number is printed. Later you will learn how to construct more comprehensible output and not just numbers.
Every line of output in the console is initiated with the >
prompt and the R command issued. Here, the output was produced by the source
function. After the last prompt you could manually enter an R command.
In the upper-right panel Environment/History/Connections/... you can see what variables currently exist and what their values are.