2.1 Getting started
In Chapter 1 we learned about the R Console and creating scripts and Projects in RStudio. We also saw how you write your R code in a script and then source this code into the console to get it to run (if you’ve forgotten how to do this, pop back to the console section to refresh your memory). Writing your code in a script means that you’ll always have a permanent record of everything you’ve done (provided you save your script) and also allows you to make loads of comments to remind your future self what you’ve done. So, while you’re working through this Chapter we suggest that you create a new script (or RStudio Project) to write your code as you follow along.
As we saw in the previous Chapter, at a basic level we can use R much as you would use a calculator. We can type an arithmetic expression into our script, then source it into the console and receive a result. For example, if we type the expression 2 + 2
and then source this line of code we get the answer 4
(reassuringly!)
2 + 2
## [1] 4
The [1]
in front of the result tells you that the observation number at the beginning of the line is the first observation. This is not much help in this example, but can be quite useful when printing results with multiple lines (we’ll see an example below). The other obvious arithmetic operators are -
, *
, /
for subtraction, multiplication and division respectively. R follows the usual mathematical convention of order of operations. For example, the expression 2 + 3 * 4
is interpreted to have the value 2 + (3 * 4) = 14
, not (2 + 3) * 4 = 20
. There are a huge range of mathematical functions in R, some of the most useful include; log()
, log10()
, exp()
, sqrt()
.
log(1) # logarithm to base e
## [1] 0
log10(1) # logarithm to base 10
## [1] 0
exp(1) # natural antilog
## [1] 2.718282
sqrt(4) # square root
## [1] 2
4^2 # 4 to the power of 2
## [1] 16
# not a function but useful
pi ## [1] 3.141593
It’s important to realise that when you run code as we’ve done above, the result of the code (or value) is only displayed in the console. Whilst this can sometimes be useful it is usually much more practical to store the value(s) in a object.