print("Hello world!")
[1] "Hello world!"
Once you’ve opened RStudio, you will see several empty panes similar to this:
Let’s focus on the console window on the left. This is where we can directly communicate with R by entering “code”. The way this code is written follows certain arbitrary conventions – just like natural languages such as English or German. Here is an example in the R programming language:
print("Hello world!")
[1] "Hello world!"
Entering this command into your console and pressing ENTER will display the sentence “Hello world!” in a new line.
As we can see, anything that R should understand as a simple sequence of letters or words must be enclosed by quotation marks "..."
. Anything inside them will be interpreted as a so-called string. Their counterpart are numbers or integers, as illustrated here:
2 + 2 - 1
[1] 3
Naturally, you can use R for more sophisticated computations:
\(2 + (3 \times 3)\)
2 + (3 * 3)
[1] 11
\(\sqrt{9}\)
sqrt(9)
[1] 3
\(\frac{16}{2^3}\)
16 / 2 ^ 3
[1] 2
While it is certainly useful to print text or numbers to your console, it may sometimes make more sense to (at least temporally) store them somewhere, so you can re-use them later. In fact, R gives us a way of storing data in virtual, container-like objects: variables. We can assign strings or numbers to a variable by using the assignment operator <-
.
When you run the commands below, you will (hopefully) notice two items popping up in your Environment/Workspace tab in the top right corner.
<- "Hello world!"
greeting
<- 2 + 2 - 1 quick_math
If we now want to display the content in the console, we can simply apply the print()
function to the variable:
print(greeting)
[1] "Hello world!"
print(quick_math)
[1] 3
We can also embed variables in other statements. For example, let’s take the content of quick_math
and multiply it with 2.
<- quick_math * 2
hard_math
print(hard_math)
[1] 6
Working with the console has a very plain, yet important disadvantage: Once we close RStudio, the console is wiped clean, erasing everything we’ve typed into it during our precious R session.
The remedy for this nuisance are scripts. Essentially, a script is the programmer’s equivalent of a Word document: It allows you to save all the code you’ve written to a file, which you can seamlessly continue working on the next time you open it.
To create a new R script you can either go to:
“File” \(\rightarrow\) “New” \(\rightarrow\) “R Script” or …
click on the icon with the + sign and select “R Script” …
or simply press Ctrl+Shift+N (MacOS: Cmd+Shift+N)
Don’t forget to save your script with Ctrl+S (Cmd+S)! It is good practice to save your files regularly.