Using the console
Entering commands directly
The console can be used to use R interactively. You can input commands at the prompt, and they will be executed if they are valid R commands. For example, an input of 1+2
at the prompt outputs [1] 3
.
1 + 2
## [1] 3
The [1]
can be ignored: [1] 3
just means that the first element of the output is 3
. This may seem strange, but is more useful when the output is longer. For example, the command 1:50
constructs a vector of integers between 1 and 50.
1:50
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
## [26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
The numbers in square brackets here are helpful in keeping track of which element of the vector each value is associated with.
You can print using the print
command.
print("Hello, World!")
## [1] "Hello, World!"
Entering commands from a script
Using the console directly is useful when you want to try out a quick command. An alternative is to gather a sequence of commands into an R script: a text file with extension “.R”.
You can create a new R script file in RStudio via
File -> New File -> R Script
You do not need to name and save the file, but you can if you like.
You can enter commands on lines of the script, and use comments (which start with #
) to explain what you are doing. Try copying and pasting the following code into your script.
1 + 2 # should be 3
3 * 4 # should be 12
# this is a for loop that prints the integers between 1 and 5
for (i in 1:5) {
print(i)
}
You can execute the whole script by clicking the “Source” button in RStudio. Alternatively, you can execute one line of the script by placing the cursor on that line and clicking “Run” or pressing Ctrl+Enter (⌘+↩︎ on macOS). This also works for executing a highlighted selection of the script.
Working on a script has the advantage that the commands you are running are stored, so you can easily re-run them or edit them.