m <- matrix(1:9, nrow = 3, ncol = 3)
m [,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
In the previous lab, you worked with vectors, which store a sequence of values of a single data type. R offers further data structures that organize values in two dimensions or combine values of different types (Figure 4.1). Vectors and matrices are homogeneous: all elements must be of the same type. Data frames and lists are heterogeneous: they can hold elements of different types. A data frame is a table in which each column is a vector of its own type, and a list is a flexible container that can hold any R object, including vectors, matrices, data frames, and other lists. In this lab, you will learn how to create, inspect, and index matrices, lists, and data frames.
A matrix is a two-dimensional array that stores elements of the same type. It has two dimensions: the number of rows and the number of columns. You can inspect the dimensions of a matrix using dim(), nrow(), and ncol().
By default, R fills a matrix column by column, starting at the top left and moving down each column before moving to the next one. To fill a matrix row by row instead, set byrow = TRUE:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
You can perform mathematical operations on matrices much as you do on vectors. However, remember that R uses recycling when operands have different lengths or dimensions, which can produce unexpected results.
For example, multiplying a matrix by a number multiplies every element by that number:
When you multiply two matrices using *, R multiplies their corresponding elements: element by element. This is different from matrix multiplication, which uses the %*% operator.
Like vectors, matrices use square brackets [] to access their elements. Because a matrix has two dimensions, you specify a row index and a column index using [row, column].
Notice that you can leave one index blank to select all rows or all columns. The colon operator : selects a sequence of indices, while c() lets you specify individual indices.
When you select a single row or column, R simplifies the result by default. For example:
The first expression returns “matrix”, while the second returns “integer” because the selected column is returned as a vector. The underlying values have not changed; only the structure of the result is different.
To preserve the matrix structure when selecting a single row or column, use drop = FALSE:
The functions cbind() and rbind() combine vectors and matrices. Both require compatible dimensions.
Use cbind() to bind by column. It places the supplied objects side by side:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 4 7 1 2 3
[2,] 2 5 8 4 5 6
[3,] 3 6 9 7 8 9
Use rbind() to bind by rows. It places the supplied objects one above the other:
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[4,] 1 2 3
[5,] 4 5 6
[6,] 7 8 9
Since both m and n have three rows and three columns, cbind(m, n) produces a matrix with three rows and six columns, whereas rbind(m, n) produces a matrix with six rows and three columns.
A list is an R object that can store elements of different types and structures. For example, a list can contain a numeric vector, a matrix, a character string, or even another list. Lists can therefore be used to group related objects, even when those objects have different types or dimensions.
The list l below contains three elements: a named numeric vector, a matrix m created earlier, and a character string.
$myValues
[1] 1 2 3
[[2]]
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[[3]]
[1] "Landsat"
Each element in a list has a position, and elements can optionally have names. In this example, the first element is named myValues, while the second and third elements are unnamed.
You can access individual elements using double square brackets [[ ]], either by name or by position:
[1] 1 2 3
[1] 1 2 3
[1] "Landsat"
If an element has a name, you can also access it using the $ operator.
Notice the difference between l[1] and l[[1]]: the first returns a list containing the first element, whereas the second returns the element itself. This distinction is important when working with lists.
You can also add elements to an existing list. For example, the following code creates an empty list and then adds the matrix n under the name nMatrix:
$nMatrix
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Lists are fundamental to R because they allow different types of objects to be stored together. Many R functions return their results as lists, including functions for linear regression, generalized linear models, and statistical tests such as t-tests. These results may include estimated coefficients, p-values, residuals, fitted values, and other information.
R provides functions to access commonly needed parts of these results. Understanding how to work with lists allows you to inspect model outputs, retrieve specific results for further analysis, and return multiple objects from your own functions.
A data frame is a two-dimensional table in which each row represents an observation and each column represents a variable. Unlike a matrix, a data frame can contain columns of different data types. For example, one column can contain numbers, another character strings, and another logical values.
The following example creates a data frame called trees containing information about four trees. The columns describe each tree’s ID, species, life status, height, diameter, and age. Some measurements are missing and are represented by NA.
treeid species life height diameter age
1 1001 Beech TRUE 34 40 110
2 1002 Fir FALSE 38 50 NA
3 1003 Pine TRUE 16 NA 40
4 1004 Fir TRUE 40 45 120
You can inspect the dimensions of a data frame using dim(), nrow(), and ncol().
The names() function returns the column names:
You can also use names() to rename columns. For example, we can change the name of the 3rd column from life to alive:
The summary() function provides a quick overview of each column. Depending on its data type, the output includes information such as minimum and maximum values, the median, the mean, or the frequency of categorical values. It can help you identify unusual values and missing data.
treeid species alive height diameter
Min. :1001 Length :4 Mode :logical Min. :16.0 Min. :40.0
1st Qu.:1002 N.unique :3 FALSE:1 1st Qu.:29.5 1st Qu.:42.5
Median :1002 N.blank :0 TRUE :3 Median :36.0 Median :45.0
Mean :1002 Min.nchar:3 Mean :32.0 Mean :45.0
3rd Qu.:1003 Max.nchar:5 3rd Qu.:38.5 3rd Qu.:47.5
Max. :1004 Max. :40.0 Max. :50.0
NAs :1
age
Min. : 40
1st Qu.: 75
Median :110
Mean : 90
3rd Qu.:115
Max. :120
NAs :1
You can access columns in a data frame in several ways. In general, selecting columns by name is preferable to selecting them by position, because column positions may change when the data frame is modified.
[1] 1001 1002 1003 1004
When you select a single column, R returns a vector by default rather than a data frame. This is often convenient when you want to perform calculations on the column. To preserve the data frame structure, use drop = FALSE.
Selecting multiple columns preserves the data frame structure.
Selecting a column does not remove it from the original data frame. It only determines what R returns as the result of the expression.
You can select rows using numerical indices. The general indexing syntax is data_frame [row_index, column_index]. The comma separates the row index from the column index.
For example, to select the second and third rows and retain all columns, use:
treeid species alive height diameter age
2 1002 Fir FALSE 38 50 NA
3 1003 Pine TRUE 16 NA 40
Leaving the column index empty means that all columns are selected. Similarly, trees[, 1] selects all rows but only the first column.
In practice, you will often want to select observations that meet specific conditions rather than select rows by their positions. Suppose we want to select all trees taller than 30 metres. The column height contains the tree heights, and trees$height accesses these values as a vector.
This expression returns a logical vector containing TRUE or FALSE for each tree. The first value corresponds to the first row, the second to the second row, and so on. A value of TRUE indicates that the corresponding tree meets the condition.
You can use this logical vector to select the matching rows.
treeid species alive height diameter age
1 1001 Beech TRUE 34 40 110
2 1002 Fir FALSE 38 50 NA
4 1004 Fir TRUE 40 45 120
R evaluates this expression from the inside out. First, trees$height accesses the height column as a vector. Next, trees$height > 30 compares each height with 30 and returns a logical vector indicating which trees are taller than 30 metres. Finally, this logical vector is used to select the corresponding rows from trees. The empty space after the comma means that all columns are retained.
You can combine multiple conditions using logical operators. For example, suppose we want trees that are both taller than 30 metres and alive:
treeid species alive height diameter age
1 1001 Beech TRUE 34 40 110
4 1004 Fir TRUE 40 45 120
Recall that %in% checks whether each element of a vector matches any value in another vector. This is useful when selecting observations that belong to a set of categories.
For example, to select trees belonging to the species Spruce, Fir, or Pine, use:
treeid species alive height diameter age
2 1002 Fir FALSE 38 50 NA
3 1003 Pine TRUE 16 NA 40
4 1004 Fir TRUE 40 45 120
Only rows whose species value matches one of these three names are selected.
In R, missing values are represented by NA. Comparisons involving missing values generally return NA rather than TRUE or FALSE.
For example, the diameter column contains a missing value:
The result contains NA for the tree whose diameter is unknown, because R cannot determine whether that diameter is greater than 40.
This matters when selecting rows using logical conditions. Consider the following expression:
treeid species alive height diameter age
2 1002 Fir FALSE 38 50 NA
NA NA <NA> NA NA NA NA
4 1004 Fir TRUE 40 45 120
Because the logical condition contains NA, R includes a row of missing values for that unknown result. This does not mean that the corresponding tree satisfies the condition; its diameter is simply unknown.
You can avoid this behaviour by explicitly excluding missing diameters using is.na():
treeid species alive height diameter age
2 1002 Fir FALSE 38 50 NA
4 1004 Fir TRUE 40 45 120
Here, !is.na(trees$diameter) identifies trees with known diameters, and & combines that condition with the requirement that the diameter be greater than 40.
The appropriate treatment of missing values depends on the analysis. You may retain observations, replace missing values using a suitable method, or exclude observations when justified.
A simple (and very crude) option is na.omit(), which returns the rows that have no missing values in any column:
treeid species alive height diameter age
1 1001 Beech TRUE 34 40 110
4 1004 Fir TRUE 40 45 120
Be aware that this can remove observations even when only one of their columns contains a missing value. This may discard useful data, so consider carefully whether it is appropriate for your analysis. More advanced approaches, including interpolation for suitable types of data, are available in packages such as zoo package.
You can create a new column by assigning values to it using the $ operator. For example, suppose the diameter is measured in centimetres and you want to create a new column containing the diameter in metres.
The new column diameter_m is added to the existing data frame. Missing values remain missing after the calculation.
You can also create a column containing a transformation of an existing variable. For example, the natural logarithm of tree height can be stored in a new column:
treeid species alive height diameter age diameter_m logHeight
1 1001 Beech TRUE 34 40 110 0.40 3.526361
2 1002 Fir FALSE 38 50 NA 0.50 3.637586
3 1003 Pine TRUE 16 NA 40 NA 2.772589
4 1004 Fir TRUE 40 45 120 0.45 3.688879
These operations leave the original columns unchanged while adding new variables that can be used in subsequent analyses.
A factor is a special type of vector used to represent categorical variables in R. Categorical variables describe groups or categories rather than numerical measurements. They can be nominal, where categories have no natural order (e.g., tree species), or ordinal, where categories have a meaningful order (e.g., small, medium, and tall).
In our trees data frame, the species column is a candidate for conversion to a factor. Currently, it is a character vector:
The function factor() converts a vector into a factor. We can store the result in a new column called class:
A factor stores a set of possible categories, called levels. In our dataset, the three levels are Beech, Fir, and Pine. You can inspect them using levels():
By default, R arranges factor levels alphabetically. You can also change the names of existing levels by assigning new labels:
treeid species alive height diameter age diameter_m logHeight class
1 1001 Beech TRUE 34 40 110 0.40 3.526361 Fagus
2 1002 Fir FALSE 38 50 NA 0.50 3.637586 Abies
3 1003 Pine TRUE 16 NA 40 NA 2.772589 Pinus
4 1004 Fir TRUE 40 45 120 0.45 3.688879 Abies
Because the original levels are ordered alphabetically (Beech, Fir, Pine), the new labels correspond to those species in that order.
A more explicit approach is to specify both the original levels and their new labels when creating the factor. This makes the mapping clear and avoids relying on the default ordering:
treeid species alive height diameter age diameter_m logHeight class
1 1001 Beech TRUE 34 40 110 0.40 3.526361 Fagus
2 1002 Fir FALSE 38 50 NA 0.50 3.637586 Abies
3 1003 Pine TRUE 16 NA 40 NA 2.772589 Pinus
4 1004 Fir TRUE 40 45 120 0.45 3.688879 Abies
Here, levels specifies the original category values, while labels defines how those categories should be represented in the resulting factor.
A factor can only contain values that are among its defined levels. Suppose we want to change the first tree’s species to “Oak”:
Warning in `[<-.factor`(`*tmp*`, 1, value = structure(c(NA, 2L, 3L, 2L), levels
= c("Fagus", : invalid factor level, NA generated
treeid species alive height diameter age diameter_m logHeight class
1 1001 Beech TRUE 34 40 110 0.40 3.526361 <NA>
2 1002 Fir FALSE 38 50 NA 0.50 3.637586 Abies
3 1003 Pine TRUE 16 NA 40 NA 2.772589 Pinus
4 1004 Fir TRUE 40 45 120 0.45 3.688879 Abies
Because “Oak” is not an existing level, R cannot assign it as a valid factor value. Instead, the entry becomes NA, and R issues a warning.
To avoid this, you must first add “Oak” as a level. You can do this by extending the existing levels:
[1] <NA> Abies Pinus Abies
Levels: Fagus Abies Pinus Oak
Now “Oak” is a valid category, and you can assign it to the first tree:
treeid species alive height diameter age diameter_m logHeight class
1 1001 Beech TRUE 34 40 110 0.40 3.526361 Oak
2 1002 Fir FALSE 38 50 NA 0.50 3.637586 Abies
3 1003 Pine TRUE 16 NA 40 NA 2.772589 Pinus
4 1004 Fir TRUE 40 45 120 0.45 3.688879 Abies
Important: Adding a level makes a category available but does not assign it to any observations. You must explicitly assign the new value where needed. Conversely, a factor may contain levels that are no longer represented in the data, for example, after filtering out all observations belonging to a particular category. You can use droplevels() to remove unused levels.
Sometimes, you may want to convert a continuous numerical variable into categories. For example, we can classify tree heights as either small or tall.
The function cut() divides a numerical variable into intervals and returns a factor indicating which interval each value belongs to.
treeid species alive height diameter age diameter_m logHeight class
1 1001 Beech TRUE 34 40 110 0.40 3.526361 Oak
2 1002 Fir FALSE 38 50 NA 0.50 3.637586 Abies
3 1003 Pine TRUE 16 NA 40 NA 2.772589 Pinus
4 1004 Fir TRUE 40 45 120 0.45 3.688879 Abies
heightClass
1 tall
2 tall
3 small
4 tall
The interval boundaries are determined by breaks. By default, cut() uses intervals that are open on the left and closed on the right, except for the first interval when include.lowest = TRUE is specified. In this example, the intervals are (0, 30] and (30, 100]. Thus, a tree with a height of exactly 30 is classified as “small”, while a tree taller than 30 is classified as “tall”.
Note that values outside the specified intervals, as well as missing values, are assigned NA. Choose the break points and labels to match the purpose of your analysis.
R can import and export data in many formats, including text files (e.g., CSV and TXT), spreadsheets (e.g., Excel), statistical software formats (e.g., SPSS), database tables, and files used by geographic information systems (e.g., DBF files). Data can also be accessed from databases and remote servers.
For an overview of supported formats, see the R Data Import/Export manual.
Text files are a common format for storing and exchanging data because they are platform-independent and can be read by many different applications. Tabular text files typically separate columns using commas, semicolons, or tabs.
The choice of separator often depends on regional conventions. For example, in many English-language settings, commas separate columns and periods indicate decimal places. In German-language settings, commas are commonly used as decimal separators, so semicolons or tabs are often used to separate columns instead.
The function read.table() is a flexible way to import tabular data from text files. Its arguments allow you to specify how the data are structured. The most important options include:
sep: the character separating columns, such as ",", ";", or "\t" for tabs.dec: the character used as the decimal separator, usually "." or ",".header: whether the first row contains column names (TRUE or FALSE).For example, the following code imports a comma-separated file with a header row and a period as the decimal separator:
The function returns a data frame. Use head() to print the first few rows and tail() to print the last few rows.
You can export a data frame to a text file using write.table(). Its arguments let you specify the column separator, decimal separator, whether to include row and column names, and how missing values should be represented.
For example, the following code writes tab to a semicolon-separated text file:
Here, row.names = FALSE prevents R from writing the row names as an additional column. By default, write.table() includes row names, which can be undesirable when exchanging data with other applications.
R also provides convenient functions for CSV files:
The function write.csv() uses commas to separate columns and periods for decimal places. Its counterpart, write.csv2(), uses semicolons to separate columns and commas for decimal places, making it convenient for many German and other European regional settings.
When importing or exporting data, R needs to know where a file is located. A file path specifies the file’s location on your computer.
The working directory is the folder R uses as the starting point for relative file paths. You can check it using getwd():
Suppose your working directory is C:/Users/Student/Documents/R_course and your files are organized as follows:
You can import the file using a relative path:
R looks for the file in the data folder relative to the working directory.
Alternatively, an absolute path specifies the complete file location:
Absolute paths work independently of the working directory but are specific to your computer. Relative paths are generally preferable when sharing projects, provided the folder structure remains unchanged.
\) with forward slashes (/) if necessary.file.choose() to open a dialog and select a file:R returns the file path as a character string, which you can copy into your import command. Because file.choose() requires manual interaction, do not use it in Markdown assignments or other scripts that should run automatically.
If R cannot find a file, check the filename, file extension, path, and working directory. You can test whether a file exists at a given path using:
The result is TRUE if the file exists and FALSE otherwise.
Recommendation: Keep your scripts and data in a clearly organized project folder. In RStudio, an RStudio Project helps you manage relative paths consistently across different computers.
For beginners, RStudio Projects and relative paths are usually sufficient. For larger projects, explicitly defined root directories can provide more flexibility.
Avoid using setwd() in scripts whenever possible. It changes the working directory for the entire R session and can make your code less portable across computers. Instead, define root directories and construct file paths using file.path():
You can also define separate root directories for input data and output files. The function file.path() automatically uses the appropriate path separator for your operating system.
This approach makes file locations explicit and easier to change, maintain, and share.