pkgs <- c("arm", "car", "caret", "cowplot", "DHARMa", "dplyr",
"e1071", "effects", "GGally", "ggdendro", "ggplot2", "gstat",
"knitr", "mapview", "moments", "MuMIn",
"rmarkdown", "sf", "SpatialKDE", "spatialreg", "spatstat",
"spdep", "stars", "terra", "tidyr", "tidyterra")
missing_pkgs <- pkgs[!nzchar(vapply(pkgs, function(p) system.file(package = p), character(1)))]
if (length(missing_pkgs) > 0) {
install.packages(missing_pkgs)
} else {
message("All packages are already installed.")
}1. Introduction to R
What is R?
R is an open-source programming language for statistics and graphics. You can use it to analyze data, apply almost any statistical technique, create graphs, and process spatial data. Because your analysis is written as code, it is easy to document, repeat, and share. R has a large user community, and thousands of add-on packages extend it for specific tasks.
Setting up R and RStudio
Complete these steps before your first lab. A tidy setup now helps you avoid most file path problems later in the course.
Install R and RStudio
R is the language and the software that runs your code. RStudio is an Integrated Development Environment (IDE) that makes writing and running R code easier. Install R first, then RStudio:
- R from CRAN. See also the HowTos for macOS and Ubuntu.
- RStudio Desktop.
Create a course folder
Create one folder for this course, for example gcg_qm, and keep your assignments and data in it. Once you are set up and have started the assignments, it should look like this:
gcg_qm/
├── gcg_qm.Rproj
├── Assignment_Lab01_YourLastName.Rmd
├── Assignment_Lab01_YourLastName.html
├── Assignment_Lab02_YourLastName.Rmd
├── ...
└── data/
├── airquality.txt
└── ...
Keep your .Rmd files directly in the course folder, not in a subfolder. The path data/airquality.txt then works both in the console and when you knit.
Download the data
R reads the unpacked files, so you need to unpack the zip file:
- Download
data.zip. - Unpack it into a folder named
datainside your course folder:- Windows: Right-click the file, select Extract All…, and click Extract. Then move the resulting
datafolder intogcg_qm. - macOS: Double-click the file, then move the resulting
datafolder intogcg_qm. - Linux: Move
data.zipinto your course folder and rununzip data.zip -d datathere.
- Windows: Right-click the file, select Extract All…, and click Extract. Then move the resulting
- Check that the files are directly in
data/, for examplegcg_qm/data/airquality.txt. The zip file contains no top-level folder, but some tools add one, which can give youdata/data/. If so, move the files up one level.
Name the folder data in lowercase, because file paths are case-sensitive on some systems.
Create an RStudio Project
An RStudio Project makes your course folder the working directory, so relative paths such as data/airquality.txt work without setwd().
- In RStudio, select File > New Project… > Existing Directory.
- Select your course folder and click Create Project.
From now on, start working by opening gcg_qm.Rproj, either by double-clicking it or via File > Open Project….
Adjust the RStudio settings
Go to Tools > Global Options… > General and change two settings:
- Uncheck Restore .RData into workspace at startup.
- Set Save workspace to .RData on exit to Never.
Each session then starts empty, so your code has to create everything it needs. This is also how knitting works, so code that runs in a fresh session is more likely to knit without errors.
By default, RStudio shows the output of R Markdown code chunks inline, directly below each chunk. This is handy, but it can cause trouble with plots that are built over several chunks, for example a plot() followed by abline() in the next chunk. We therefore recommend unchecking Show output inline for all R Markdown documents under Tools > Global Options… > R Markdown. Chunk output then appears in the console and the Plots pane, just like the output of your scripts.
Install R packages
An R package is a collection of functions and other resources that extend R’s capabilities. Packages are often designed for specific tasks, such as data manipulation or visualization. Some packages come with the R installation, while others must be installed separately using install.packages().
Before you install packages, make sure you have the most recent version of R. You can check your version with R.version.string in the console. Packages built for the current R version may not be available for older versions, and packages installed under one R version have to be reinstalled after updating R.
The labs use a number of add-on packages. Install them all at once by copying the following code into the RStudio console and pressing Enter. The code installs only the packages that are not installed yet, so you can run it again later without harm:
The installation can take several minutes. If R asks whether to use a personal library, answer yes. If it asks whether to install packages from source that need compilation, answer no.
To install a single package that is missing or not in the list above, pass its name in quotes to install.packages(), for example:
install.packages("ggplot2")You only need to install a package once, unless you want to update or reinstall it. Do not include install.packages() in your homework markdowns. However, you must load the package in each markdown file and new R session in which you want to use it:
Packages are updated regularly. To update the packages you have already installed, run:
update.packages()Running R code
You give R instructions by writing code, which the R interpreter executes. In RStudio (Figure 3.1), you can run code in two ways:
- Type it into the Console and press Enter. R runs it immediately.
- Write it into a Script (a text file) and send single lines or a selection to the console with Ctrl+Enter (Cmd+Enter on macOS). Scripts keep your code, so you can re-run and change your analysis later.
Most results appear in the console, while graphs appear in the Plots pane.
To check your setup, open your project and run these lines in the console:
getwd()
file.exists("data/airquality.txt")getwd() should return the path to your course folder, and file.exists() should return TRUE. If it returns FALSE, check that the project is open and that the file is in the data folder. See Work with Markdown before you complete your first assignment.
First steps in R
Expressions and assignments
If an expression is given as a command, it is evaluated, printed (unless specifically made invisible), and the value is lost.
2 + 5[1] 7
An assignment also evaluates an expression and passes the value to a variable but the result is not automatically printed. The assignment operator is <- (“less than” and “minus”).
a <- 2 + 5Variable names can contain letters, digits, . and _, and must start with a letter (or with . not followed by a digit). R is case sensitive, so a and A are different variables.
If you enter the name of an existing variable into the console, its content is printed to the console output.
a[1] 7
If you assign a new expression to an already existing variable, this variable is overwritten.
b <- 5
a <- a + b
a[1] 12
Workspace
The entities that R creates and manipulates are known as objects. These may be variables, arrays of numbers, character strings, and functions. The objects are stored in your current working environment (also called workspace). Once you quit an R session, these objects cease to exist.
The function ls() can be used to display the names of objects in your current workspace:
ls()[1] "a" "b" "q"
The function rm() can be used to remove objects from the workspace:
rm(b)
ls()[1] "a" "q"
R Markdown documents run in their own workspace when you knit them. An R Markdown document therefore does not see the objects of your interactive workspace, and all objects it uses must be created by code inside the document.
Getting help
You can see the help for each R function using ?:
?is.nanYou can even get help for help:
?helpData types
Objects can store different types of data: numbers (double and integer), text (character), and logical values (TRUE and FALSE). Each type can also hold missing values. You can use the function typeof() to identify the data type.
Integer and double
The common numeric data types in R are integer and double. An integer is a whole number (without decimal places). A double stores real-valued numbers approximately. R treats numeric values as double by default. Doubles have finite precision, so some values cannot be represented exactly.
a <- 7
typeof(a)[1] "double"
You can explicitly define an integer using a capital L.
b <- 7L
typeof(b)[1] "integer"
The / operator returns a value of type double, even when both operands are integers.
typeof(7L / 2L)[1] "double"
7L / 2L[1] 3.5
Character
d <- "hello world"
typeof(d)[1] "character"
Combine two or more character variables with paste(). The default separator (sep) is a single space.
paste("Hello", "World")[1] "Hello World"
paste("Hello", "World", sep = "_")[1] "Hello_World"
Extract a portion of a character variable with substring():
substring("Hello World", first = 3, last = 8)[1] "llo Wo"
Logical
The logical data type has the values TRUE and FALSE; NA can represent a missing logical value. T and F are available as aliases, but they are ordinary variables and can be overwritten, so prefer TRUE and FALSE.
typeof(TRUE)[1] "logical"
Missing values
When an element or value is “not available” or a “missing value” in the statistical sense, a place within a vector may be reserved for it by assigning it the special value NA.
Many arithmetic and comparison operations involving NA return NA.
3 == NA[1] NA
To evaluate if a variable contains a missing value use is.na():
is.na(3)[1] FALSE
There is a second kind of “missing” values which are produced by numerical computation, the so-called Not a Number, NaN, values.
0 / 0[1] NaN
is.na() is TRUE both for NA and NaN values. To differentiate these, is.nan() is only TRUE for NaNs.
is.na(0 / 0)[1] TRUE
is.nan(0 / 0)[1] TRUE
is.nan(NA)[1] FALSE
Type coercion
R includes functions to set or change the data type:
as.character(a)[1] "7"
as.integer("3.1")[1] 3
as.double("3.1")[1] 3.1
Converting to integer cuts off the decimal places without rounding. If a value cannot be converted, R returns NA and gives a warning:
as.integer(3.9)[1] 3
as.double("abc")Warning: NAs introduced by coercion
[1] NA
Math operators and functions
There are several mathematical operators already implemented in R:
a <- 7
b <- 5
d <- a * b + sqrt(a) - b^2 / log(2) * 1.34 * exp(b)
d[1] -7135.204
The elementary arithmetic operators are the usual +, -, *, / and ^ for raising to a power.
In addition, all common mathematical functions are available, e.g.:
sqrt(x): square root of xexp(x): exponential of x (e^x)log(x, base = n): log to base n of x (default base is e, natural log)log10(x): log to base 10 of xsin(x): sine of x in radianscos(x): cosine of x in radians- …and more
Comparison and logical operators
Logical values are the result of evaluating a condition. Comparison operators compare two values: == (equal), != (not equal), <, <=, >, and >=.
a == b # is a equal to b ?[1] FALSE
a != b # is a not equal to b ?[1] TRUE
a < b # is a less than b ?[1] FALSE
a > b # is a greater than b ?[1] TRUE
The %in% operator evaluates whether each element of the first vector is also part of the second vector. The operator returns a logical vector of the same length as the first vector.
x <- c(3, 9)
y <- c(1, 2, 3, 4, 5)
x %in% y[1] TRUE FALSE
Logical operators combine conditions: & (AND), | (OR), and ! (NOT).
a > b & a < 10 # both conditions are TRUE[1] TRUE
a < b & a < 10 # only the second condition is TRUE[1] FALSE
a < b | a < 10 # at least one condition is TRUE[1] TRUE
!(a < b)[1] TRUE
Logical operators can sometimes determine a result even when one value is missing. TRUE | NA is TRUE, because the result is TRUE whatever the missing value is. TRUE & NA, in contrast, is NA.
TRUE | NA[1] TRUE
TRUE & NA[1] NA
Vectors
A vector is an ordered collection of values from a single data type. Use c() to combine different values into a vector:
x <- c(1, 3, 8, 12, 56, 875, 234, 13)
x[1] 1 3 8 12 56 875 234 13
Use length() to determine the number of values in a vector:
length(x)[1] 8
You can construct vectors from each data type:
y <- c("a", "b", "c")
typeof(y)[1] "character"
When values of different types are combined, R coerces them to a common type. The usual coercion order is logical < integer < double < complex < character, so character values cause the whole vector to become character:
z <- c(1, 4, "b", 8.5, "abc")
typeof(z)[1] "character"
Vectorized operations
To apply an arithmetic operation to each element of a vector, you may be tempted to write a loop. The loop below goes through each element i of vector x and multiplies it by 2.
x[1] 1 3 8 12 56 875 234 13
for (i in x) {
print(i * 2)
}[1] 2
[1] 6
[1] 16
[1] 24
[1] 112
[1] 1750
[1] 468
[1] 26
For simple elementwise calculations, R’s vectorized operations are usually more concise and faster than a loop. The expressions below apply multiplication and addition to each element of x; these are vectorized operations.
x * 2[1] 2 6 16 24 112 1750 468 26
x + 2[1] 3 5 10 14 58 877 236 15
Vectorized operations also work between two vectors. In the following example, the first elements are added together, the second elements are added together, and so forth.
x <- c(1, 2, 3, 4, 5, 6, 7, 8)
y <- c(6, 3, 6, 9, 3, 1, 7, 2)
x + y[1] 7 5 9 13 8 7 14 10
Recycling of vectors
If two vectors have different lengths, the shorter vector is recycled (repeated) as often as needed to match the length of the longer vector. In the example below, the y vector gets recycled four times to c(1, 2, 1, 2, 1, 2, 1, 2).
x <- c(1, 2, 3, 4, 5, 6, 7, 8)
y <- c(1, 2)
x + y[1] 2 4 4 6 6 8 8 10
Here, y gets recycled twice to c(1, 5, 1, 3, 1, 5, 1, 3).
x <- c(1, 2, 3, 4, 5, 6, 7, 8)
y <- c(1, 5, 1, 3)
x + y[1] 2 7 4 7 6 11 8 11
R still recycles y if its length is not a multiple of the length of x, but it gives a warning because the recycling is incomplete.
x <- c(1, 2, 3, 4, 5, 6, 7, 8)
y <- c(1, 5, 3)
x + yWarning in x + y: longer object length is not a multiple of shorter object
length
[1] 2 7 6 5 10 9 8 13
Statistical functions
Statistical functions summarize all values of a vector in a single number. Common examples are:
min()andmax(): smallest and largest valuesum()andprod(): sum and product of all valuesmean()andmedian(): arithmetic mean and medianvar()andsd(): variance and standard deviation
x[1] 1 2 3 4 5 6 7 8
mean(x)[1] 4.5
sd(x)[1] 2.44949
Some related functions return a vector instead of a single number. For example, range() returns the minimum and maximum, and cumsum() returns the cumulative sum at each position of the vector.
range(x)[1] 1 8
cumsum(x)[1] 1 3 6 10 15 21 28 36
Because arithmetic with NA returns NA, statistical functions return NA when the vector contains even a single missing value. This reminds you that your data are incomplete. To ignore missing values in the calculation, set the argument na.rm = TRUE.
y <- c(1, 5, NA, 3)
sum(y)[1] NA
sum(y, na.rm = TRUE)[1] 9
Logical vectors
A comparison applied to a vector returns a logical vector with one value per element. all() tests whether all values are TRUE, and any() tests whether at least one value is TRUE.
x[1] 1 2 3 4 5 6 7 8
x < 4[1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
all(x < 4)[1] FALSE
any(x < 4)[1] TRUE
When arithmetic functions are applied to logical vectors, TRUE is treated as the number 1 and FALSE is treated as the number 0. This can be very handy when counting the number of true values.
x[1] 1 2 3 4 5 6 7 8
sum(x < 4)[1] 3
Generating vectors
Sequences
The function seq() generates a sequence of numbers. You set the start (from), the end (to), and either the step size (by) or the number of values (length.out):
seq(from = 1, to = 100, by = 10) [1] 1 11 21 31 41 51 61 71 81 91
seq(from = 0, to = 1, length.out = 5)[1] 0.00 0.25 0.50 0.75 1.00
For sequences of whole numbers with a step size of 1, the : operator is a shortcut. 1:10 gives the same values as seq(from = 1, to = 10, by = 1). If the first number is larger than the second, the sequence counts down:
1:10 [1] 1 2 3 4 5 6 7 8 9 10
15:5 [1] 15 14 13 12 11 10 9 8 7 6 5
Repeats
The function rep() repeats a value or a vector. The argument times repeats the whole vector, while each repeats every element before moving on to the next:
rep("x", times = 10) [1] "x" "x" "x" "x" "x" "x" "x" "x" "x" "x"
rep(c("x", "o"), times = 5) [1] "x" "o" "x" "o" "x" "o" "x" "o" "x" "o"
rep(c("x", "o"), each = 5) [1] "x" "x" "x" "x" "x" "o" "o" "o" "o" "o"
You can combine rep() with seq() or :, for example to create a grouping variable for an experiment with three treatments and four replicates each, or sampling depths repeated for two sites:
rep(1:3, each = 4) [1] 1 1 1 1 2 2 2 2 3 3 3 3
rep(seq(from = 0, to = 30, by = 10), times = 2)[1] 0 10 20 30 0 10 20 30
Numerical indexing
Each value in a vector has a position, starting at 1 for the first value. You can access the ith value of a vector x by writing its position in square brackets, x[i]. To access several values at once, use a vector of positions, for example created with c() or ::
x <- c(1, 3, 8, 12, 56, 875, 234, 13)
x[1][1] 1
x[c(1, 5)][1] 1 56
x[c(1:4, 8)][1] 1 3 8 12 13
The last value is at position length(x). If you ask for a position beyond the end of the vector, R returns NA:
x[length(x)][1] 13
x[10][1] NA
Removing values of a vector
A negative index returns the vector without the value at that position. To drop several values, use a vector of negative positions:
x[1] 1 3 8 12 56 875 234 13
x[-3][1] 1 3 12 56 875 234 13
x[-c(1, 2)][1] 8 12 56 875 234 13
This does not change x itself. To keep the result, assign it to a variable:
x2 <- x[-3]
length(x)[1] 8
length(x2)[1] 7
Overwriting values of a vector
You can also overwrite individual values in a vector by assigning a new value to its position:
x[1] <- 5
x[1] 5 3 8 12 56 875 234 13
Logical indexing
Instead of positions, you can use a condition to select values. The condition x > 100 tests every value of x and returns a logical vector of the same length. Used as an index, this logical vector selects all values where it is TRUE:
x[1] 5 3 8 12 56 875 234 13
x > 100[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE FALSE
x[x > 100][1] 875 234
You can combine conditions with & and |:
x[x > 10 & x < 100][1] 12 56 13
The same index also works for overwriting values. Here, all values larger than 100 are set to 100:
x[x > 100] <- 100
x[1] 5 3 8 12 56 100 100 13
Watch out: if the logical index is shorter than x, R recycles it. For example, c(TRUE, FALSE) selects every second value. Unlike recycling in arithmetic, R gives no warning, even if the length of the index is not a multiple of length(x). Make sure your logical index has the same length as x.
x[c(TRUE, FALSE)][1] 5 8 56 100
x[c(TRUE, FALSE, TRUE)][1] 5 8 12 100 100
Citing R
When you use R in a report or thesis, cite it. The function citation() returns the reference for the R version you use:
citation()To cite R in publications use:
R Core Team (2026). _R: A Language and Environment for Statistical
Computing_. R Foundation for Statistical Computing, Vienna, Austria.
doi:10.32614/R.manuals <https://doi.org/10.32614/R.manuals>.
<https://www.R-project.org/>.
A BibTeX entry for LaTeX users is
@Manual{,
title = {R: A Language and Environment for Statistical Computing},
author = {{R Core Team}},
organization = {R Foundation for Statistical Computing},
address = {Vienna, Austria},
year = {2026},
doi = {10.32614/R.manuals},
url = {https://www.R-project.org/},
}
We have invested a lot of time and effort in creating R, please cite it
when using it for data analysis. See also 'citation("pkgname")' for
citing R packages.
Comments
Comments start with a hash mark (
#). Everything that follows the hash mark up to the end of the line is ignored by the R interpreter. Comments can be entire lines or follow R code.