2 An introduction to the R language
While R is a general purpose programming language, its main purpose is to provide a specialized programming environment for data analysis, and this is reflected in the language design. R was created by statisticians, for statisticians, and has not seen as widespread an adoption, as for example Python.
As with any language, be it a natural or a programming language, we first need to master
some basic vocabulary. This includes both operators
and functions
. We will
focus on how to use functions. This is followed by a look at the
fundamental data types, leading us to the most important object for
statisticians applications, the data frame. We will look at a modern version
of the data frame, the tibble
, which in many ways is an improvement over the
old data frame. We will thus often refer to data frames, even when we are
technically working with tibbles.
Software in R is intended to be written in a functional style. This means that computations are organized around applying functions to data. A consequence of this is that we will not place a great emphasis on iteration (e.g. for
loops) and similar constructs. While R does support object-orientation, including a system called S3
, which is rather easy to use, it is not central to the language in the same way as it is to other languages.
2.1 Operators and functions
To start with, let’s look at some arithmetic and logical operators. Operators
are generally used between two arguments, like this: 1 + 2
. This is known as
infix notation. Function, on the other hand, are applied to their arguments
like so: abs(x)
. Operators in R are just special functions, which are allowed
to be used inbetween two operands. The operator +
is actually a function; it
can also be used a function. In this case, it needs to be surrounded by
backticks
`+`(1, 2)
Operators can be broadly grouped into arithmetic, relational and logical operators. The latter are used to perform comparisons between two objects, and to perform Boolean operations.
2.1.1 Arithmetic operators
The first five should be self-explanatory:
+ addition
- subtraction
* multiplication
/ division
^ or ** power
x %*% y matrix multiplication c(5, 3) %*% c(2, 4) == 22
x %% y modulo (x mod y) 5 %% 2 == 1
x %/% y whole number division: 5 %/% 2 == 2
The last three operators may be new to you. %*%
is the operator for [matrix multiplication] (https://en.wikipedia.org/wiki/Matrix_multiplication). %%
is the modulo operator. This finds the remainder after division, e.g. 5 %% 2
(5 modulo 2) is equal to 1. %/%
is used for whole number division, e.g. 5 %/% 2
is equal to 2 (how many times is 2 contained in 5?). These operators are often used for programming.
The last three operators have the form % %
. It is actually possible to define any function as an infix operator, surrounded by %
. E.g. %in%
is an operator that checks if its first operand is contained in the second operand.
2.1.2 Logical operators and functions
You probably won’t need the last two functions, xor()
and isTRUE()
very often.
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal
!x not x (negation)
x | y x OR y
x & y x AND y
xor(x, y) exclusive OR (either in x or y, but not in both)
isTRUE(x) truth test for x
The following provides a visual overview of the logical operators using Venn diagrams. x
refers to the left circle, y
to the right circle.
2.1.3 Some basic numerical functions
The following is a list of some functions that are used for mathematical
operations. For instance log()
computes the natural logarithm of its argument.
We can compute the logarithm to any base using the functions second argument base
.
abs(x) absolute value
sqrt(x) square root
ceiling(x) round up: ceiling(3.475) is 4
floor(x) round down: floor(3.475) is 3
round(x, digits=n) round: round(3.475, digits=2) is 3.48
cos(x), sin(x), tan(x), acos(x), cosh(x), acosh(x) etc.
log(x) natural logarithm
log(10, base = n) base n logarithm
log2(x) base 2 logarithm
log10(x) base 10 logarithm
exp(x) exponential function: e^x
Every operator in R is actually a function that is allowed to use infix notation. E.g. +
can be used both as an operator and as a function. This requires that the operator be surrounded by backticks (```). The benefit of this is not immediately apparent; however, it can very useful for advanced programming techniques.
2.1.4 Using R as a calculator
We are ready to do some basic math. Try out the following examples in the R console.
# addition
5 + 5
12321 + 343224
# subtraction
6 - 5
5 - 89
# multiplication
3 * 5
34 * 54
# division
4 / 9
(5 + 5) / 2
# parentheses are important
(3 + 7 + 2 + 8) / (4 + 11 + 3)
1/2 * (12 + 14 + 10)
1/2 * 12 + 14 + 10
# power
3^2
2^12
# exponential function
exp(5)
# the next result is given in scientific notation:
# 1.068647 * 10^13
exp(30)
# whole number division
# 6 is contained 5 times in 33, with remainder 3
33 %% 6 # remainder: 3
#> [1] 3
33 %/% 6 # contained 5 times
#> [1] 5
5 %% 2 # remainder 1
#> [1] 1
5 %/% 2 # contained twice
#> [1] 2
# logical operators
3 > 2
#> [1] TRUE
4 > 5
#> [1] FALSE
4 < 4
#> [1] FALSE
4 <= 4
#> [1] TRUE
5 >= 5
#> [1] TRUE
6 != 6
#> [1] FALSE
9 == 5 + 4
#> [1] TRUE
!(3 > 2)
#> [1] FALSE
(3 > 2) & (4 > 5) # AND
#> [1] FALSE
(3 > 2) | (4 > 5) # OR
#> [1] TRUE
xor((3 > 2), (4 > 5))
#> [1] TRUE
Exercise
Calculate the following:
\(\frac{1}{3}*\frac{1+3+5+7+2}{3 + 5 + 4}\)
\(e\) (you have to calculate this)
\(\sqrt{2}\)
\(\sqrt[3]{8}\)
\(sin(2*\pi)\)
\(log_2(8)\)
2.1.5 Statistical functions
Here is a list of statistical functions. These have in common that they can have
the argument na.rm
, which is set to FALSE
by default. This lets us deal with
missing values (na
stands for not available). If set to false, these are not removed (rm
stands for remove).
mean(x, na.rm = FALSE) mean
sd(x) standard deviation
var(x) variance
median(x) median
quantile(x, probs) quantile of x. probs: vector of probabilities
sum(x) sum
min(x) minimal value of x (x_min)
max(x) maximal value of x (x_max)
range(x) x_min und x_max
# if center = TRUE: subtract mean
# if scale = TRUE: divide by sd
scale(x, center = TRUE, scale = TRUE) center and standardize
# weighted sampling with argument prob:
sample(x, size, replace = FALSE, prob) sampling with or without replacement
prob: vector of weights
2.1.6 Further useful functions
One of the most often used functions is c()
. This stands for combine or
concatenate; it is used to combine individual elements into a vector.
c() combine: used to create a vector
seq(from, to, by) generates a sequence
: colon operator: generates a sequence in increments of 1
rep(x, times, each) repeats x
times: sequence is repeated n times
each: each element is repeated n times
head(x, n = 6) show first 6 elements of x
tail(x, n = 6) show last 6 elements of x
2.1.7 Examples
# this creates a vector consisting of the elements 1 to 6
c(1, 2, 3, 4, 5, 6)
#> [1] 1 2 3 4 5 6
mean(c(1, 2, 3, 4, 5, 6))
#> [1] 3.5
mean(c(1, NA, 3, 4, 5, 6), na.rm = TRUE)
#> [1] 3.8
mean(c(1, NA, 3, 4, 5, 6), na.rm = FALSE)
#> [1] NA
sd(c(1, 2, 3, 4, 5, 6))
#> [1] 1.870829
sum(c(1, 2, 3, 4, 5, 6))
#> [1] 21
min(c(1, 2, 3, 4, 5, 6))
#> [1] 1
range(c(1, 2, 3, 4, 5, 6))
#> [1] 1 6
# output:
# attr(,"scaled:center")
# [1] 3.5
# this is the mean
scale(c(1, 2, 3, 4, 5, 6), scale = FALSE)
#> [,1]
#> [1,] -2.5
#> [2,] -1.5
#> [3,] -0.5
#> [4,] 0.5
#> [5,] 1.5
#> [6,] 2.5
#> attr(,"scaled:center")
#> [1] 3.5
# output (additionally):
# attr(,"scaled:scale")
# [1] 1.870829
# this is the standard deviation
scale(c(1, 2, 3, 4, 5, 6), scale = TRUE)
#> [,1]
#> [1,] -1.3363062
#> [2,] -0.8017837
#> [3,] -0.2672612
#> [4,] 0.2672612
#> [5,] 0.8017837
#> [6,] 1.3363062
#> attr(,"scaled:center")
#> [1] 3.5
#> attr(,"scaled:scale")
#> [1] 1.870829
# sampling with replacement
sample(c(1, 2, 3, 4, 5, 6), size = 1, replace = TRUE)
#> [1] 5
sample(c(1, 2, 3, 4, 5, 6), size = 12, replace = TRUE)
#> [1] 4 5 6 4 6 1 5 5 5 2 6 3
# weighted sampling with replacement:
sample(c(1, 2, 3, 4, 5, 6), size = 1, replace = TRUE,
prob = c(4/12, 1/12, 1/12, 2/12, 2/12, 2/12 ))
#> [1] 5
sample(c(1, 2, 3, 4, 5, 6), size = 12, replace = TRUE,
prob = c(4/12, 1/12, 1/12, 2/12, 2/12, 2/12 ))
#> [1] 1 2 5 1 4 5 5 1 1 1 4 6
# the following two examples create a sequence from 1 to 6. This gives the same
# result as c(1, 2, 3, 4, 5, 6)
seq(from = 1, to = 6, by = 1)
#> [1] 1 2 3 4 5 6
1:6
#> [1] 1 2 3 4 5 6
rep(1:6, times = 2)
#> [1] 1 2 3 4 5 6 1 2 3 4 5 6
rep(1:6, each = 2)
#> [1] 1 1 2 2 3 3 4 4 5 5 6 6
rep(1:6, times = 2, each = 2)
#> [1] 1 1 2 2 3 3 4 4 5 5 6 6 1 1 2 2 3 3 4 4 5 5 6 6
Exercise
Generate a sequence from 0 to 100 in increments of 5.
Calculate the mean of of the vector [1, 3, 4, 7, 11, 2].
What is the range \(x_{\mathrm{max}} - x_{\mathrm{min}}\) of this vector?
What is its sum?
Center the vector.
Simulate a coin flip using
sample()
. Tip: heads is 1 and tails is 0. Can you simulate 100 coin flips?Simulate a trick coin with \(p \neq 0.5\).
Generate a vector consisting of the number 3 100 times.
Solution
# 1)
seq(0, 100, by = 5)
#> [1] 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90
#> [20] 95 100
# 2)
c(1, 3, 4, 7, 11, 2)
#> [1] 1 3 4 7 11 2
mean(c(1, 3, 4, 7, 11, 2))
#> [1] 4.666667
# 3)
max(c(1, 3, 4, 7, 11, 2)) - min(c(1, 3, 4, 7, 11, 2))
#> [1] 10
# 4)
sum(c(1, 3, 4, 7, 11, 2))
#> [1] 28
# 5) center
scale(c(1, 3, 4, 7, 11, 2), scale = FALSE)
#> [,1]
#> [1,] -3.6666667
#> [2,] -1.6666667
#> [3,] -0.6666667
#> [4,] 2.3333333
#> [5,] 6.3333333
#> [6,] -2.6666667
#> attr(,"scaled:center")
#> [1] 4.666667
# 6)
sample(c(1, 0), size = 1, replace = TRUE)
#> [1] 1
sample(c(1, 0), size = 100, replace = TRUE)
#> [1] 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 0 0 1 1 0 0 1 0 1 1 1 0 1 0 1 0 0 1 0 0 0
#> [38] 1 0 1 0 1 0 1 0 0 0 1 1 0 0 1 1 0 0 0 1 0 1 1 0 0 1 0 0 0 1 0 0 0 0 0 1 1
#> [75] 1 0 1 1 1 1 0 1 1 1 0 0 1 1 1 1 0 1 1 0 0 0 1 1 1 1
# 7) trick coin
sample(c(1, 0), size = 100, replace = TRUE, prob = c(5/6, 1/6))
#> [1] 1 1 1 0 1 0 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 1
#> [38] 0 1 1 1 1 1 1 1 1 0 1 0 1 1 1 1 1 0 1 1 0 1 1 0 1 1 0 1 0 1 1 1 0 1 1 1 0
#> [75] 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 1
# 8)
rep(3, times = 100)
#> [1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
#> [38] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
#> [75] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
2.2 Defining variables
Variables are usually defined in R using the asssignment arrow <-
: my_var <- 4
.
<-
is the assignment operator and consists of a <
sign and a -
. Since
this is tedious to type, you can also use the key combination ALT
+ -
.
In R, we can use both <-
and =
for assignment. R purists prefer <-
, mainly for historical reasons. There is a difference; =
is used for assigning values to arguments, whereas <-
should not be used for this.
Interestingly, there is also a right assignment arrow ->
, although use of this is generally not recommended.
2.2.1 Variable names
A variable needs a name. This must consist of letters, numbers and may contain
_
(underscore) and/or .
(period). A name must begin with a letter, and may not contain
spaces.
There are a few conventions. We recommend using snake_case
for variable names, e.g. my_var
.
Other options are:
snake_case_variable
camelCaseVariable
variable.with.periods
variable.With_noConventions
# good variable names
x_mean
x_sd
num_people
age
# not so good
p
a
# bad variable names
x mean
sd of x
Many programmers tended to use .
in variable names instead of _
. Modern style
guides do not recommend this, because it can lead
to confusion when using S3
object orientation.
After defining a variable my_var
and assigning the value 4 to it:
we can see its value in the console:
Check the Environment pane. You should see new variables appearing there.
Exercise
Practise defining some new variables:
Solution
vector <- c(1, 3, 4, 7, 11, 2)
vector
#> [1] 1 3 4 7 11 2
sum_of_vector <- sum(vector)
sum_of_vector
#> [1] 28
mean_of_vector <- mean(vector)
mean_of_vector
#> [1] 4.666667
rounded_mean <- round(mean_of_vector, digits = 1)
rounded_mean
#> [1] 4.7
These variablesnow exist in the Global Environment, but will no longer be available if we restart R.
2.3 Function calls
Let’s take a closer look at the syntax of R function calls.
The function shown below consists of a name function_name
and two arguments,
arg1
and arg2
. The arguments may have default values. In this example,
arg1
doesn’t have a default value, but arg2
has the default value val2
.
Arguments with no default value are required, whereas arguments with a
default value are not. These simply take their default value if no value is
provided.
function_name(arg1, arg2 = val2)
A function may have many arguments.
The following illustrates the difference between using =
or <-
for
assignment and using =
for passing arguments to functions.
# assignment:
# `<-` assigns a value to an object:
x <- c(23.192, 21.454, 24.677)
# or
x = c(23.192, 21.454, 24.677)
# arguments of functions:
# `=` for passing function arguments with values:
round(x, digits = 1)
#> [1] 23.2 21.5 24.7
Use <-
for assignment, =
for assigning values to function arguments.
If you want to test for equivalence, use the ==
operator.
Exercise
Use tab
completion for function arguments:
At the R prompt, enter
scale(
and pressTAB
.What are the arguments of the function
round()
? Do any have default values?Look up the
rnorm()
function in the Help Viewer. What arguments? Any default values?Do the same for the
seq()
function.What do the following function calls do?
seq()
seq(1, 10)
seq(1, 10, by = 2)
seq(1, 10, length.out = 20)
Solution
seq()
#> [1] 1
seq(1, 10)
#> [1] 1 2 3 4 5 6 7 8 9 10
seq(1, 10, by = 2)
#> [1] 1 3 5 7 9
seq(1, 10, length.out = 20)
#> [1] 1.000000 1.473684 1.947368 2.421053 2.894737 3.368421 3.842105
#> [8] 4.315789 4.789474 5.263158 5.736842 6.210526 6.684211 7.157895
#> [15] 7.631579 8.105263 8.578947 9.052632 9.526316 10.000000
2.3.1 Nested function calls
Function calls can be nested. This means that the output of one function is passed as input to the next function.
For example: Let’s define a vector, compute its mean and then round to two decimal places:
# define a vector:
c(34.444, 45.853, 21.912, 29.261, 31.558)
#> [1] 34.444 45.853 21.912 29.261 31.558
# compute mean:
mean(c(34.444, 45.853, 21.912, 29.261, 31.558))
#> [1] 32.6056
# round:
round(mean(c(34.444, 45.853, 21.912, 29.261, 31.558)),
digits = 2)
#> [1] 32.61
Function calls are always performed in the same order: from innermost to outermost, e.g. first mean()
and then round()
.
2.4 Data types
Vectors are the fundamental data type in R - all other data types are composed of vectors. These can subdivided into:
numeric vectors: a further subdivision is into
integer
(whole numbers) unddouble
(floating point numbers).character vectors: these consist of characters strings and are surrounded by quotes, either single
'
or double"
, e.g.'word'
oder"word"
.logical vectors: these can take three values:
TRUE
,FALSE
orNA
.
Vectors consist of elements of the same type, i.e., we cannot combine logical
and character
elements in a vector. Vectors have three properties:
- Type:
typeof()
: what is it? - Length:
length()
: how many elements? - Attribute:
attributes()
: additional metadata
Vectors are created using the c()
function or by using special function, such as seq()
or rep()
.
2.4.1 Numeric vectors
Numeric vectors consist of integers or floating point numbers.
We can subset vectors, i.e. select individual elements from a vector using []
:
# the first element:
numbers[1]
#> [1] 1
# the second element:
numbers[2]
#> [1] 2.5
# the last element:
# numbers has length 3
length(numbers)
#> [1] 3
# we can use this for subsetting
numbers[length(numbers)]
#> [1] 4.5
# with - (minus) we can omit an element, e.g. the first
numbers[-1]
#> [1] 2.5 4.5
# we can use a sequence
numbers[1:2]
#> [1] 1.0 2.5
# we can omit the first and third elements
numbers[-c(1, 3)]
#> [1] 2.5
Matrices
A matrix is a special kind of vector in R. It is basically a vector that has an additional dim
(dimension) attribute:
The following code illustrates how you can create a matrix by changing the
dimensions of a vector, or by using the matrix()
function.
# x is a vector
x <- 1:8
# we can define the dimensions of x
dim(x) <- c(2, 4)
x
#> [,1] [,2] [,3] [,4]
#> [1,] 1 3 5 7
#> [2,] 2 4 6 8
# we can also create a matrix like this:
m <- matrix(x <- 1:8, nrow = 2, ncol = 4, byrow = FALSE)
m
#> [,1] [,2] [,3] [,4]
#> [1,] 1 3 5 7
#> [2,] 2 4 6 8
# what are its dimensions?
dim(m)
#> [1] 2 4
We are using the argument byrow
, which has the default value FALSE
. If we set this to true (byrow = TRUE
) we obtain:
m2 <- matrix(x <- 1:8, nrow = 2, ncol = 4, byrow = TRUE)
m2
#> [,1] [,2] [,3] [,4]
#> [1,] 1 2 3 4
#> [2,] 5 6 7 8
Now, the rows are filled in first.
Matrices can be transposed, i.e. the rows become the columns and vice versa:
There are two further functions that are often used for creating matrices: cbind()
and rbind()
.
cbind()
combines columns of several objects:
x1 <- 1:3
# x1 is a vector
x1
#> [1] 1 2 3
x2 <- 10:12
# x2 is a vector
x2
#> [1] 10 11 12
m1 <- cbind(x1, x2)
# m1 is a matrix with dimensions [3, 2]
m1
#> x1 x2
#> [1,] 1 10
#> [2,] 2 11
#> [3,] 3 12
You can try out something similar with rbind()
:
m2 <- rbind(x1, x2)
# m2 is a matrix with dimensions [2, 3]
m2
#> [,1] [,2] [,3]
#> x1 1 2 3
#> x2 10 11 12
Just like vectors, matrices can be subset using []
. Note that here we need to
specify both rows and columns: [row, column]
, separated by a comma. If either
row or column is omitted, R selects all rows or columns.
Vectorization
Everything in R is vectorized, i.e. all functions and operators automatically
operate on whole vectors. E.g. if we create a vector x1
and then add the
number 2 to x1
, this is added to each element of x1
.
x1 <- 1:10
x1 + 2
#> [1] 3 4 5 6 7 8 9 10 11 12
x2 <- 11:20
x1 + x2
#> [1] 12 14 16 18 20 22 24 26 28 30
# element-wise multiplication
x1 * x2
#> [1] 11 24 39 56 75 96 119 144 171 200
x1^2
#> [1] 1 4 9 16 25 36 49 64 81 100
The same applies to functions:
x1 <- 1:10
exp(x1)
#> [1] 2.718282 7.389056 20.085537 54.598150 148.413159
#> [6] 403.428793 1096.633158 2980.957987 8103.083928 22026.465795
If you want to compute the sine of a vector:
Recycling
Something to be aware of is vector recycling
: This means that if we perform an
operation with two vectors that don’t have the same length, the shorter vector
is repeated. E.g. if we add two vectors, we get:
This is what is happening here:
1 2 3 4 5 6 7 8 9 10
1 2 1 2 1 2 1 2 1 2
The vector 1:2
is repeated as often as necessary.
What happens if the length of the longer vector is not a mupliple of the length of the shorter vector?
1:10 + 1:3
#> Warning in 1:10 + 1:3: Länge des längeren Objektes
#> ist kein Vielfaches der Länge des kürzeren Objektes
#> [1] 2 4 6 5 7 9 8 10 12 11
R will give us a warning in this case.
1 2 3 4 5 6 7 8 9 10
1 2 3 1 2 3 1 2 3 1
Missing Values
Missing values are declared with NA
.
We can use the function is.na()
to test for missing values:
Missing values are not the same as Inf
(infinity) and NaN
(not a number). These occur for instance when you try to divide by zero: 1/0
or 0/0
. A further data type is NULL
; this is used when something should exist but remains undefined.
2.4.2 Character vectors
Character vectors (strings) are used to represent text:
text <- c("these are", "some", "words")
text
#> [1] "these are" "some" "words"
typeof(text)
#> [1] "character"
# text has 2 elements:
length(text)
#> [1] 3
letters
and LETTERS
are so called built-in constants
. They contain all letters in the English language.
?letters
letters[1:3]
#> [1] "a" "b" "c"
letters[10:15]
#> [1] "j" "k" "l" "m" "n" "o"
LETTERS[24:26]
#> [1] "X" "Y" "Z"
A useful function for creating character vectors is:
paste(LETTERS[1:3], letters[24:26], sep = "_")
#> [1] "A_x" "B_y" "C_z"
# special case with sep = ""
paste0(1:3, letters[5:7])
#> [1] "1e" "2f" "3g"
first_name <- "Ronald Aylmer"
last_name <- "Fisher"
paste("My name is:", first_name, last_name, sep = " ")
#> [1] "My name is: Ronald Aylmer Fisher"
The tidyverse
package stringr offers many
useful functions for working with strings. We will see examples of this in later
chapters.
2.4.3 Logical vectors
Logical vectors can take exactly 3 values; TRUE
, FALSE
or NA
.
Logical vectors can be used for indexing other vectors. For example, we might want to extract all elements of a vector that are greater than some value, e.g. all positive numbers.
set.seed(5434) # makes the example reproducible
# draw 10 random numbers from a Gaussian distribution
x <- rnorm(10, mean = 0, sd = 1)
x
#> [1] 1.06115528 0.87480990 -0.30032832 1.21965848 0.09860288 1.89862128
#> [7] -1.54699798 0.96349219 -0.64968432 -1.09672125
# we want all positive numbers:
x > 0
#> [1] TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE FALSE FALSE
# we can use this to index x:
x[x > 0]
#> [1] 1.06115528 0.87480990 1.21965848 0.09860288 1.89862128 0.96349219
# we can also save the index
index <- x > 0
# and use this:
x[index]
#> [1] 1.06115528 0.87480990 1.21965848 0.09860288 1.89862128 0.96349219
2.4.4 Factors
The numeric
, logical
, and character
vectors we have met so far are atomic vectors
, because they are the fundamental data types.
For categorical data, used for grouping, we need a further object type. This is
known as a factor
. A factor
is simply a vector of integers, with additional
metadata (attributes). These consist of the object class factor
and the factor
levels
.
# this is a character vector indicating the sex of a sample of people
sex <- c("male", "female", "male", "male", "female")
sex
#> [1] "male" "female" "male" "male" "female"
typeof(sex)
#> [1] "character"
# this has no attributes
attributes(sex)
#> NULL
We can define a factor:
sex <- factor(sex, levels = c("female", "male"))
sex
#> [1] male female male male female
#> Levels: female male
# sex hast type integer
typeof(sex)
#> [1] "integer"
# but `class` factor
class(sex)
#> [1] "factor"
# and attributes levels und class
attributes(sex)
#> $levels
#> [1] "female" "male"
#>
#> $class
#> [1] "factor"
If we don’t explicitly define the levels, R just uses alphabetical ordering.
We can obtain the integer values of a factor by using unclass()
.
sex
#> [1] male female male male female
#> Levels: female male
unclass(sex)
#> [1] 2 1 2 2 1
#> attr(,"levels")
#> [1] "female" "male"
Representing categorical variables as factors is essential for linear models,
and for plotting. For example, if we use dummy coding in a linear model, the
first factor level will automatically be chosen as the reference category. We
can change the ordering using relevel()
or factor()
.
Usingrelevel()
:
levels(sex)
#> [1] "female" "male"
# the result has to be reassigned to the variable
sex <- relevel(sex, ref = "male")
levels(sex)
#> [1] "male" "female"
We can also use factor()
, but then we need to provide all levels:
sex <- factor(sex, levels = c("male", "female"))
sex
#> [1] male female male male female
#> Levels: male female
2.4.4.1 A new way of working with factors: forcats
The above operations can all be performed using the tidyverse
package forcats.
Re-levelling a factor can be performed using the function fct_relevel()
:
This will change the ordering of the factor levels, so that "male"
becomes the
first level. This function has many more options, which are explained in the
functions help page.
2.4.5 Lists
The next data types are lists. Whereas atomic vectors must be composed of elements of the same type, lists can contain heterogeneous elements (including other lists).
We can define a list using the function list()
:
x <- list(1:3, "a", c(TRUE, FALSE, TRUE), c(2.3, 5.9))
x
#> [[1]]
#> [1] 1 2 3
#>
#> [[2]]
#> [1] "a"
#>
#> [[3]]
#> [1] TRUE FALSE TRUE
#>
#> [[4]]
#> [1] 2.3 5.9
This list contains a numeric vector, a character, a logical vector and another numeric vector.
Lists can be indexed just like vectors:
x[1]
#> [[1]]
#> [1] 1 2 3
x[2]
#> [[1]]
#> [1] "a"
x[3]
#> [[1]]
#> [1] TRUE FALSE TRUE
x[4]
#> [[1]]
#> [1] 2.3 5.9
Lists can also be indexed using double square brackets, [[
. Whereas the single square bracket [
returns a list containing just that list elements, double square brackets [[
return the actual contents of the list element. This is explained very well in R for Data Science.
Lists are very important in R; most statistical functions actually create lists as outputs, and it is useful to know how to deal with these.
Lists can also have named
elements:
x <- list(int = 1:3,
string = "a",
log = c(TRUE, FALSE, TRUE),
double = c(2.3, 5.9))
x
#> $int
#> [1] 1 2 3
#>
#> $string
#> [1] "a"
#>
#> $log
#> [1] TRUE FALSE TRUE
#>
#> $double
#> [1] 2.3 5.9
x is a named list
. This makes subsetting easier - there is a special operator,
the $
operator, which can be used for selecting named elements of a list. This
can be used together with tab
completion. If you type x$
at the R prompt, R
will show all named elements.
As an example, the following code performs a two sample t test, and saves the results in a list.
We can inspect the elements of the list. E.g. the P value can be retrieved like this:
2.4.6 Data frames
We now come to the most important objects for statistics: data frames. They are used to represent data.
A data frame is a two-dimensional structure with rows and columns. Technically,
a data frame is a list whose elements are equal length vectors. These vectors
can be numeric
, logical
,character
or factors, for categorical (grouping)
variables. A data frame can be subset in the same way as a matrix, or as a list.
A modern version of data frames are referred to as tibbles
or tbl_df
.
tibbles
are created using the function tibble()
.
Let’s create a data frame. We will first use the data.frame()
function, and
then create the same data frame using the tibble()
function which is provided
by both the dplyr
or tibble
packages, both of which are automatically loaded
when we load the tidyverse
package.
The two main advantages of using tibbles are that (1) strings are never automatically converted into factors, which can lead to problems, and that (2) they have a much nicer print method.
df <- data.frame(sex = factor(c("male", "female",
"male", "male",
"female")),
age = c(22, 45, 33, 27, 30))
df
#> sex age
#> 1 male 22
#> 2 female 45
#> 3 male 33
#> 4 male 27
#> 5 female 30
library(tidyverse)
#> ── Attaching packages ────── tidyverse 1.3.0 ──
#> ✓ tibble 2.1.3 ✓ purrr 0.3.3
#> ✓ tidyr 1.0.2 ✓ dplyr 0.8.4
#> ✓ readr 1.3.1 ✓ stringr 1.4.0
#> ── Conflicts ───────── tidyverse_conflicts() ──
#> x dplyr::filter() masks stats::filter()
#> x dplyr::lag() masks stats::lag()
df <- tibble(sex = factor(c("male", "female",
"male", "male",
"female")),
age = c(22, 45, 33, 27, 30))
df
#> # A tibble: 5 x 2
#> sex age
#> <fct> <dbl>
#> 1 male 22
#> 2 female 45
#> 3 male 33
#> 4 male 27
#> 5 female 30
df
is a data frame (or tibble) with two variables, sex
and age
. This data
frame should appear in the Environment pane (under Data):
A data frame has the attributes names()
, colnames()
und rownames()
; names()
und colnames()
refer to the same thing.
attributes(df)
#> $names
#> [1] "sex" "age"
#>
#> $row.names
#> [1] 1 2 3 4 5
#>
#> $class
#> [1] "tbl_df" "tbl" "data.frame"
The length of a data frame is the length of the list, i.e. the number of
colummns. We can also use ncol()
. To get the number of rows, we can use
nrow()
.
Data frame subsetting
Data frames can be subset as a list, or as a matrix.
- as a list: columns (variables) can be selected using
$
or[
- as a matrix: elements can be selected using
[
# choose variables
df$sex
#> [1] male female male male female
#> Levels: female male
df$age
#> [1] 22 45 33 27 30
df["sex"]
#> # A tibble: 5 x 1
#> sex
#> <fct>
#> 1 male
#> 2 female
#> 3 male
#> 4 male
#> 5 female
df["age"]
#> # A tibble: 5 x 1
#> age
#> <dbl>
#> 1 22
#> 2 45
#> 3 33
#> 4 27
#> 5 30
# by position
df[1]
#> # A tibble: 5 x 1
#> sex
#> <fct>
#> 1 male
#> 2 female
#> 3 male
#> 4 male
#> 5 female
df[2]
#> # A tibble: 5 x 1
#> age
#> <dbl>
#> 1 22
#> 2 45
#> 3 33
#> 4 27
#> 5 30
We can also select rows and columns, just as we would do with a matrix: [row, column]
.
# row 1, column 1
df[1, 1]
#> # A tibble: 1 x 1
#> sex
#> <fct>
#> 1 male
# row 1, all columns
df[1, ]
#> # A tibble: 1 x 2
#> sex age
#> <fct> <dbl>
#> 1 male 22
# all rows, column 1
df[, 1]
#> # A tibble: 5 x 1
#> sex
#> <fct>
#> 1 male
#> 2 female
#> 3 male
#> 4 male
#> 5 female
# all rows, all columns
df[ , ]
#> # A tibble: 5 x 2
#> sex age
#> <fct> <dbl>
#> 1 male 22
#> 2 female 45
#> 3 male 33
#> 4 male 27
#> 5 female 30
# first 3 rows, all columns
df[1:3, ]
#> # A tibble: 3 x 2
#> sex age
#> <fct> <dbl>
#> 1 male 22
#> 2 female 45
#> 3 male 33
We can also index individual columns (variables):
2.5 Exercises
Rounding numbers
x <- rnorm(10, mean = 1, sd = 0.5)
x
#> [1] 0.7233677 0.8530281 1.2907552 0.9243246 1.8349864 0.9463656 1.2581664
#> [8] 0.6762927 1.0524451 0.5225796
this_number <- 3.45263
- Round the vector
x
to 0 decimal places. - Round the vector
x
to 3 decimal places. - Round the number
this_number
to the nearest whole number.
Compute mean
df <- tibble(sex = sample(c("male", "female"),
size = 24,
replace = TRUE),
age = runif(24, min = 19, max = 45))
df
#> # A tibble: 24 x 2
#> sex age
#> <chr> <dbl>
#> 1 female 26.3
#> 2 female 36.1
#> 3 male 29.1
#> 4 male 32.6
#> 5 male 30.9
#> 6 male 31.8
#> # … with 18 more rows
- In this data frame, compute the mean age.
- Have a look at the summary statistics using the
summary()
function.
Character vectors
Generate a new variable from the variables ID
, initials
and age
using the
paste()
function. The new variable should look like this:
"1-RS-44" "2-MM-78" "3-PD-22" "4-PG-34" "5-DK-67" "1-RS-59"
Data frames
Change the order of the factor levels in the following data set. We want
placebo
to be the new reference category.
library(tidyverse)
alc_aggr <- tibble(no_alcohol = c(64, 58, 64),
placebo = c(74, 79, 72),
anti_placebo = c(71, 69, 67),
alcohol = c(69, 73, 74))
alc_aggr <- alc_aggr %>%
pivot_longer(everything(), names_to = "condition", values_to = "aggression") %>%
mutate(condition = as_factor(condition))
alc_aggr
#> # A tibble: 12 x 2
#> condition aggression
#> <fct> <dbl>
#> 1 no_alcohol 64
#> 2 placebo 74
#> 3 anti_placebo 71
#> 4 alcohol 69
#> 5 no_alcohol 58
#> 6 placebo 79
#> # … with 6 more rows
levels(alc_aggr$condition)
#> [1] "no_alcohol" "placebo" "anti_placebo" "alcohol"
Advanced exercise
Even numbers
- Select all even numbers from a numeric vector:
Hint: you will need to use the modulo operator
%%
. Even numbers are divisible by 2, i.e. there is no remainder when diving by 2.
Solution
# if the remainder is 0, then the element is even
x %% 2 == 0
#> [1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
#> [13] FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
Odd numbers
- Do the same for the odd numbers.
Operators are used like this:
1 + 2
; they are written between the operands (infix notation). Functions are used like this:abs(x)
; they are applied to arguments.