In this lesson we will practice what we learned so far. Remember: All R code is below the "R Source" button, while the output is hidden by default. To see it you will need to click on the "R Output" button. Importantly, at the bottom of the page, you will find a bar which allows you to change the theme of the webpage (changing colors and format) so it can easily adapt to your system and preferences. There you also find "Code highlighting" which changes how R code is displayed to you, and Toggle R code and Figures.

Practicals

These are a few exercises that should help you get acquainted with R. You should calculate or evaluate the R expressions before pressing the "R Output" button.

R commands can sometimes be rather difficult to follow, so occasionally it can be useful to annotate them with comments. This can be done by typing a hash (#) character: any further text on the same line is ignored by R. Copy the code below onto your Source pane (top-left) and run it while reading the comments.

If, however, you would like to train by yourself, rather than in the website, here's a link for the R code so you can download it and run in your own computer.

# this is a comment: R will ignore it
1 + 1 # this queals to two

[1] 2

# The symbol * means multiply, and ^ means 'to the power', so this gives 5
# times (10 squared), i.e. 500
5 * 10^2

[1] 500

# A different function: 'sqrt' takes a single argument, returning its square
# root.
sqrt(25)

[1] 5

# The result of a function can be used as part of a further analysis
sqrt(25 - 9) + 100

[1] 104

# For example, let's learn about the function max() This function returns
# the maximum value of all its arguments
max(-10, 0.2, 4.5)

[1] 4.5

# Now you can use results of functions as arguments to other functions
sqrt(2 * max(-10, 0.2, 4.5))

[1] 3

# The log() function returns the logarithm of its first argument
log(100)

[1] 4.60517

# By default this is the natural logarithm (base 'e')
log(2.718282)

[1] 1

# But you can change the base of the logarithm using the 'base' argument
log(100, base = 10)

[1] 2

log10(100)

[1] 2

# R knows about infinity (and minus infinity)
1/0

[1] Inf

-1/0

[1] -Inf

# undefined results take the value NaN ('not a number')
0/0

[1] NaN

# for the mathematically inclined, you can force R to use complex numbers
sqrt(0+0i - 9)

[1] 0+3i

# R has another special symbol for 'empty'
sum(c(1, 2, NULL, 4))