print("Hello world!")[1] "Hello world!"
Once you’ve opened RStudio, you will see several empty panes similar to the ones shown here:
Let’s focus on the console window on the left. This is where we can communicate with R directly 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:
Entering this command into your console and pressing Enter will display the sentence "Hello world!" on a new line.
As we can see, anything that R should understand as a simple sequence of letters or words must be enclosed in quotation marks "...". Anything inside them will be interpreted as a so-called string. Their counterparts are numbers, as illustrated here:
Naturally, you can use R for more sophisticated computations:
\(2 + (3 \times 3)\)
\(\sqrt{9}\)
\(\frac{16}{2^3}\)
While it is certainly useful to print text or numbers to your console, it may sometimes make more sense to store them somewhere (at least temporarily) so that you can reuse them later. 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 tab in the top-right corner.
If we now want to display their contents in the console, we can simply apply the print() function to the variables:
We can also embed variables in other statements. For example, let’s take the content of quick_math and multiply it by 2:
Working with the console has a simple but 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 is the script. 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 …
go to File > New File > R Script,
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 (macOS: Cmd+S)! It is good practice to save your files regularly.