2 + 2[1] 4
4 * (3 + 5) # The sum within brackets is executed first[1] 32
pi / 4 # Pi over four[1] 0.7853982
Programming and Data Analysis with R

“Everything should be made as simple as possible, but not simpler”
Attributed to Albert Einstein
This unit will cover the following topics:
In class the code is written live, following the R script of this unit. These notes contain the same material and are there for you to consult at any time.
First of all, R can be used as if it were a scientific calculator:
2 + 2[1] 4
4 * (3 + 5) # The sum within brackets is executed first[1] 32
pi / 4 # Pi over four[1] 0.7853982
To compute the power a^b one uses:
2^5 # Alternative syntax: 2**5[1] 32
The quantities \sqrt{2} and \sin(\pi/4) are instead obtained with the commands:
sqrt(2)[1] 1.414214
sin(pi / 4)[1] 0.7071068
A value can be stored by assigning it to an object through the symbol <-.
# Assign the value sqrt(5) to the object x
x <- sqrt(5) # Alternative syntax (not recommended): x = sqrt(5)The value contained in x can later be recalled, modified and saved into a new object, called for instance y.
y <- x + pi # That is, pi plus the square root of 5
y[1] 5.377661
To remove an object from memory one uses the command rm, that is, remove.
rm(x) # x is no longer present in the "workspace"It is good practice to keep the workspace, that is the working environment, clean.
If an object is no longer needed, it can be deleted through the command rm.
The list of the objects saved in memory can be displayed with the following command:
ls() # The object y is present in the workspace[1] "y"
Therefore, to delete all the saved objects, one can use
rm(list = ls())Let us suppose that x is a real number.
What follows is a list of functions available in R:
x <- 1 / 2 # Example of a real numberexp(x) # Exponential and natural logarithm[1] 1.648721
log(x)[1] -0.6931472
abs(x) # Absolute value[1] 0.5
sign(x) # Sign function[1] 1
sin(x) # Trigonometric functions (sine, cosine, tangent)[1] 0.4794255
cos(x)[1] 0.8775826
tan(x)[1] 0.5463025
Let us suppose that x and y are two real numbers. Moreover, let n and k be two natural numbers.
x <- 1 / 2 # Real numbers
y <- 1 / 3
n <- 5 # Natural numbers
k <- 2factorial(n) # n![1] 120
choose(n, k) # Binomial coefficient[1] 10
round(x, digits = 2) # Rounds x using 2 decimal digits[1] 0.5
floor(x) # Rounds x down to the nearest integer[1] 0
ceiling(x) # Rounds x up to the nearest integer[1] 1
In R it is possible to draw any function through the command curve.
If for example we consider the function f(x) = \frac{\sin(x)}{x}, then we can draw f(x) over the interval (0,15) as follows:
curve(sin(x) / x, from = 0, to = 15)
The documentation of R is the main source of information.
What is a function for? What is the definition of its arguments? The answer should always be looked for in the official documentation and not in these notes.
The command ? function opens a window in which a function is described in detail. Example:
# Run the following command in the console to open the documentation
# of the log function:
# ? logVery large numbers, such as 10^{15}, and very small ones, such as 10^{-15}, are represented in R as follows:
10^15[1] 1e+15
10^(-15)[1] 1e-15
Because of numerical approximation, when a number is too large R returns Inf, that is infinity. For example:
10^1000 # A very large number, although finite[1] Inf
The symbol NaN means instead Not a Number and is obtained when some mathematical function has not been used in the correct way. For example:
log(-1) # This command also generates a warningWarning in log(-1): NaNs produced
[1] NaN
It is well known that \sin(\pi) = 0. However, in R one obtains a number very close to 0, but strictly positive. Indeed:
sin(pi)[1] 1.224647e-16
R is a numerical computing tool and therefore numerical approximation errors are always present.
Fortunately, in most practical cases the difference between 0 and 10^{-16} is completely irrelevant.
In other situations, numerical approximation errors may lead to misleading conclusions. One should therefore be careful and evaluate case by case.
In any case, the numerical approximation may also turn out to be exact. For example:
cos(pi)[1] -1
In R it is often necessary to check whether one or more conditions are satisfied or not.
x <- 5
x < 0 # Is the value of x smaller than 0?[1] FALSE
a <- (x == -3) # Is the value of x equal to -3?
a[1] FALSE
The value of a is a binary or boolean indicator, that is, it can be true (TRUE) or false (FALSE).
Other logical functions available (assuming that y is a number and b a boolean) are:
a <- TRUE
b <- FALSE
x <- 5
y <- 7
x >= y # Is x greater than or equal to y? (Use "<=" for smaller or equal)[1] FALSE
x != y # Is x different from y?[1] TRUE
a & b # a AND b. Are the boolean values a and b both true?[1] FALSE
a | b # a OR b. Is at least one of a and b true?[1] TRUE
A vector in R is defined through the function c(), as in the following example:
x <- c(4, 2, 2, 8, 10)
x[1] 4 2 2 8 10
The following object is a vector in R, even though the object x is made of both numbers and letters
x <- c("A", "B", 2, 8, 10)
x[1] "A" "B" "2" "8" "10"
Sometimes it is convenient to create vectors whose elements are consecutive numbers
x <- 5:10 # Equivalent to: x <- c(5, 6, 7, 8, 9, 10)
x[1] 5 6 7 8 9 10
To create a sequence of real numbers one uses the command seq:
x <- seq(from = 0, to = 1, by = 0.1)
x [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
To create a vector of repeated values one uses the command rep:
x <- rep(10, 7) # Vector in which the number 10 is repeated 7 times
x[1] 10 10 10 10 10 10 10
Most of the mathematical functions of R are vectorized. In other words, the functions act on all the elements of a vector.
exp(1:6) + (1:6) / 2 + 1 # Example 1[1] 4.218282 9.389056 22.585537 57.598150 151.913159 407.428793
x <- c(10, 10^2, 10^3, 10^4, 10^5, 10^6) # Example 2
log(x, base = 10)[1] 1 2 3 4 5 6
1:8 > 4 # Example 3[1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE
Other functions are instead useful precisely when the argument is a vector:
x <- c(2, 3, 1, 3, 10, 5)
length(x) # Length of the vector[1] 6
sum(x) # Sum of the elements of the vector[1] 24
cumsum(x) # Cumulative sums[1] 2 5 6 9 19 24
Further simple operations in which the argument is a vector are listed below:
x <- c(2, 3, 1, 3, 10, 5)
prod(x) # Product of the elements of the vector[1] 900
cumprod(x) # Cumulative products[1] 2 6 6 18 180 900
sort(x, decreasing = FALSE) # Vector sorted in increasing order[1] 1 2 3 3 5 10
min(x) # Minimum value[1] 1
which.min(x) # Position of the value corresponding to the minimum[1] 3
Finally, the behaviour of the following functions should be guessable from what we have seen so far:
max(x) # Maximum value[1] 10
which.max(x) # Position of the value corresponding to the maximum[1] 5
range(x) # Equivalent to: c(min(x), max(x))[1] 1 10
It is possible to select the elements of a vector using square brackets, as in the following examples:
# Concatenation of vectors
x <- c(rep(pi, 2), sqrt(2), c(10, 7))
x[3] # Extracts the third element from the vector x, that is sqrt(2)[1] 1.414214
x[c(1, 3, 5)] # Extracts the first, the third and the fifth element[1] 3.141593 1.414214 7.000000
x[-c(1, 3, 5)] # Deletes the first, the third and the fifth element[1] 3.141593 10.000000
x[x > 3.5] # Extracts the elements greater than 3.5[1] 10 7
The last command suggests that the elements of a vector can be selected through a condition on the vector itself.
What happens when two vectors of different length are summed?
In this first example, R at least returns a warning.
x <- 1:5
y <- 1:6
x + y # Equivalent to: c(x, x[1]) + yWarning in x + y: longer object length is not a multiple of shorter object
length
[1] 2 4 6 8 10 7
In this second example, instead, R does not return any warning, which makes the situation particularly dangerous
x <- 1:3
y <- 1:6
x + y # Equivalent to: c(x, x) + y[1] 2 4 6 5 7 9
A matrix {\bf A} is a table of numbers a_{ij}, where i is the row and j is the column. For example, the matrix
{\bf A} = \begin{pmatrix}
5 & 2\\
1 & 4 \\
\end{pmatrix}, can be defined in R through the command matrix, listing the elements column by column:
A <- matrix(c(5, 1, 2, 4), nrow = 2, ncol = 2)
A [,1] [,2]
[1,] 5 2
[2,] 1 4
It is possible to select the elements of a matrix in a way analogous to what was done with vectors.
A[1, 2] # Extraction of the element in position (1,2)[1] 2
A[, 2] # Extraction of the second column[1] 2 4
A[1, ] # Extraction of the first row[1] 5 2
Some basic commands to manipulate matrices are the following
dim(A) # Returns the dimension of the matrix[1] 2 2
diag(A) # Returns the diagonal of the matrix[1] 5 4
The commands cbind and rbind put vectors (or matrices) side by side, as columns or as rows, respectively. We will use them to collect results into a table.
x <- c(1, 2, 3)
y <- c(10, 20, 30)
cbind(x, y) # x and y as columns x y
[1,] 1 10
[2,] 2 20
[3,] 3 30
rbind(x, y) # x and y as rows [,1] [,2] [,3]
x 1 2 3
y 10 20 30