R for Biochemists @UAM
  • Home
  • Course Contents
    • R1: Variables, Operators and data structures
    • R2: Flow Control
    • R3: Read and write data in R
    • R4: Functions in R
    • R5: Plotting your data in R
    • R6: Advanced data management
    • R7: Project management for reproducible research in R
    • R8: R for Molecular Biology

On this page

  • 1 Working directory and file paths in R
    • 1.1 Quick exercise (I): file paths in Windows
    • 1.2 Quick exercise (II): working directory
    • 1.3 Quick exercise (III): relative paths
  • 2 Reading & writing data in R
    • 2.1 Quick exercise (IV): choosing an import function
    • 2.2 Quick exercise (V): comma or semicolon?
    • 2.3 Reading data example
    • 2.4 Quick exercise (VI): data frame or matrix?
    • 2.5 Writing tables and saving R objects
    • 2.6 Quick exercise (VII): save() or saveRDS()?
    • 2.7 Quick exercise (VIII)
  • 3 Basic Data Management in R
    • 3.1 Open and explore a data frame
    • 3.2 Quick exercise (IX): exploring a data frame
    • 3.3 Quick exercise (X): complete the code
    • 3.4 Renaming, changing and adding variables
    • 3.5 Dealing with NAs
    • 3.6 Quick exercise (XI): missing values
    • 3.7 Quick exercise (XII)
    • 3.8 Quick exercise (XIII)
  • 4 References
  • 5 Review exercises
  • 6 Extra (short) exercises
  • 7 Session Info

R3: Read and write data in R

Input
Output
Read
Write
Path
Working Directory
Published

August 16, 2024

Modified

November 6, 2026

1 Working directory and file paths in R

When working with R, we often need to read data from files and write results back to disk. These files can be simple text files, comma-separated tables, spreadsheet exports (e.g. MS Excel files), or more specialised formats used in biological data analysis.

Before reading or writing files, R needs to know where to look for them. By default, R reads and writes files in the current working directory (wd). You can think of the working directory as the folder where R is currently “standing”.

The wd is indicated in the Console panel, as you can see below in a screenshot of my RStudio screen right now.

Note that the abbreviation ~ stands for your home directory. For example, this may correspond to /Users/modesto in macOS, /home/modesto in Linux, or C:/Users/your_user_name in Windows.

The functions getwd() and setwd() allow you to check and change the wd. Try the examples below and pay attention to the output. Remember that you can write ?getwd() or ?setwd() for help.

WarningFile paths in different operating systems

File paths are written differently depending on the operating system. Linux and macOS use forward slashes (/), whereas Windows usually displays paths with backslashes (\). In R, however, it is safer and simpler to write Windows paths using forward slashes (/) or double backslashes (\\), because a single backslash has a special meaning inside character strings.

For example, this Windows path:

C:\Users\Ana\Documents\HPBBM2025\data

can be written in R as:

"C:/Users/Ana/Documents/HPBBM2025/data"

or as:

"C:\\Users\\Ana\\Documents\\HPBBM2025\\data"

The following example was generated in a Windows 11 computer. However, unless otherwise indicated, most of the examples and exercises in this site were generated under macOS or Ubuntu and should be adapted if you want to try them out in Windows.

# Windows example
# First, check where R is currently looking for files.
# This is useful before reading or writing any file.
getwd()
[1] "C:/Users/MR.5052598/OneDrive - UAM/Documentos/GitHub/r4biochemists.github.io"
# Now we change the working directory to an existing folder.
# Notice that, even in Windows, we use forward slashes (/).
setwd("C:/Users/MR.5052598")
getwd()
[1] "C:/Users/MR.5052598"
# Intentional mistake 1: typo in the folder name.
# "Documnts" does not exist, so setwd() should return an error.
# This is a common source of problems when file paths are typed manually.
setwd("C:/Users/MR.5052598/Documnts")
Error in `setwd()`:
! no es posible cambiar el directorio de trabajo
# Intentional mistake 2: invalid/unwanted character at the end of the path.
# The extra ">" makes the path different from the real folder name.
# This is useful to show that file paths must match exactly.
setwd("C:/Users/MR.5052598/Documents")

# If the previous command worked, this would show the new working directory.
# Since the line above is intentionally wrong, this helps students see that
# the working directory has not changed as expected.
getwd()
[1] "C:/Users/MR.5052598/Documents"

In RStudio, the default working directory can be set from the Tools > Global Options menu. You can also change the wd for your session in Session > Set Working Directory, selecting the folder of the source file, the current file location, or a folder selected in the Files panel.

TipWouldn’t it be great if you didn’t have to manually set the working directory every time?

If setting the working directory feels annoying or confusing, you can avoid it by using an R Project in RStudio, as explained in Lesson R7. R Projects automatically manage the working directory for you, making your workflow smoother and more reproducible.


1.1 Quick exercise (I): file paths in Windows

Imagine that your course data folder is located here in Windows:

C:\Users\Ana\Documents\HPBBM2025\data

Which path is safest and simplest to use in R?

Select the right answer

1.2 Quick exercise (II): working directory

Let’s see if you understood. Consider the following tree of directories.

How would you change the wd to the folder HPBBM2023/data? You can also try this with your own computer and your own directory tree.

Select the right answer

1.3 Quick exercise (III): relative paths

Suppose your current working directory is:

HPBBM2025/

and inside it you have this folder structure:

HPBBM2025/
├── data/
│   └── small_matrix.csv
├── scripts/
└── results/

Which command reads small_matrix.csv without changing the working directory?

Select the right answer

2 Reading & writing data in R

A common first step in data analysis is importing a file into R. In this lesson, we will focus on tabular text files, such as .txt or .csv files. These files store data in rows and columns, using a separator character to divide the fields.

The base R function read.table() is a flexible function for reading tabular data. Several commonly used functions, such as read.csv() and read.csv2(), are convenient wrappers around read.table() with different default options.

For example:

  • read.table() is general and flexible, but often requires specifying arguments such as sep, header or dec.
  • read.csv() is designed for comma-separated files, usually using , as field separator and . as decimal separator.
  • read.csv2() is common in European spreadsheet exports, usually using ; as field separator and , as decimal separator.

2.1 Quick exercise (IV): choosing an import function

You have a file named measurements.csv with the following structure:

sample,temperature,pH
A,37.0,7.2
B,36.5,7.4
C,38.1,7.1

Which function would be the simplest first choice to import this file?

Select the right answer

2.2 Quick exercise (V): comma or semicolon?

A file exported from a spreadsheet program looks like this:

sample;temperature;pH
A;37,0;7,2
B;36,5;7,4
C;38,1;7,1

Which function is most appropriate as a first attempt?

Select the right answer


2.3 Reading data example

In the following example, we read a file called small_matrix.csv, located in the data folder.

Although the file contains numerical values arranged like a matrix, read.table() imports it as a data frame. A data frame is a very useful structure for tabular data, but some matrix-specific functions may require explicitly converting it into a matrix with as.matrix().

sm <- read.table("small_matrix.csv", sep=",")
Warning in file(file, "rt"): no fue posible abrir el archivo
'small_matrix.csv': No such file or directory
Error in `file()`:
! no se puede abrir la conexión
# Intentional mistake: we tried to read the file as if it were located
# directly in the working directory.
# However, the file is actually inside the data/ folder.
# This should return an error such as "cannot open the connection".
#
# When a file cannot be found, the first useful diagnostic step is
# to check the working directory.
getwd()
[1] "C:/Users/MR.5052598/OneDrive - UAM/Documentos/GitHub/r4biochemists.github.io"
# Correct version: include the relative path from the working directory
# to the file. Here, the file is inside the data/ folder.
sm <- read.table("data/small_matrix.csv", sep=",")

# Print the object to inspect the imported table.
sm
  V1 V2 V3
1  2  7 19
2 22 10 80
3 18  3 13
4 25  6 16
# Important point: read.table() imports tabular data as a data frame,
# even if all values are numeric.
is.matrix(sm)
[1] FALSE
# Some functions, such as t(), may work because R can coerce the object
# to a matrix when possible.
t(sm)
   [,1] [,2] [,3] [,4]
V1    2   22   18   25
V2    7   10    3    6
V3   19   80   13   16
# Arithmetic operations may also work if all columns are numeric.
sm * 3
  V1 V2  V3
1  6 21  57
2 66 30 240
3 54  9  39
4 75 18  48
# Intentional problem: diag() expects a matrix-like object.
# Depending on the object structure, this may fail or behave unexpectedly.
diag(sm)
Error in `diag()`:
! 'list' object cannot be coerced to type 'double'
# Correct approach: explicitly convert the data frame into a matrix.
diag(as.matrix(sm))
[1]  2 10 13
# Same idea with heatmap(): it is a matrix-oriented function.
# The first call is intentionally included to show what happens if we
# pass a data frame directly.
heatmap(sm)
Error in `heatmap()`:
! 'x' must be a numeric matrix
# Correct approach: convert the data frame explicitly.
heatmap(as.matrix(sm))

2.4 Quick exercise (VI): data frame or matrix?

After importing a numerical table with read.table(), you obtain an object called sm.

Which command checks whether sm is a matrix?

Select the right answer

Which command converts sm into a matrix?

Select the right answer

Tip

Note that read.table() and its wrappers read.csv() or read.csv2() are mostly used for reading data frames. If you want to read text files, like in the case of biological sequences, you can use other functions, such as readLines(), described in Lesson R8.

2.5 Writing tables and saving R objects

Once you have created or modified an object in R, you may want to save it. There are two common situations:

  1. Saving a table as a text file, so that it can be opened by other programs.
  2. Saving R objects, so that they can be loaded again in R with their structure preserved.

For tables, we can use functions such as write.table(), write.csv() or write.csv2(). For R objects, we can use save(), load(), saveRDS() or readRDS().

You can write any data object as a binary data file or as a text file. Compare the different files saved in the code below.

# Create two simple example objects.
vector <- c(1:5)
vector2 <- c(3, 5:13)

# write() writes a simple vector to a text file.
# This is useful for simple objects, but not usually the best option
# for complete data frames.
write(vector2,file="data/vector2.txt")

# write.table() writes a tabular object to a text file.
# Intentional issue for discussion: by default, write.table() writes
# row names and column names and uses spaces as separator.
# Open the resulting file and compare it with sm2.csv below.
write.table(sm,"data/sm.csv")

# Here we explicitly control the output:
# - row.names = FALSE avoids saving row numbers as an extra column.
# - col.names = FALSE avoids saving column names.
# - sep = "," creates comma-separated values.
write.table(sm,"data/sm2.csv", row.names = FALSE, col.names=FALSE, sep=",")

# save() stores one or more R objects in a binary RData file.
# When loaded again, the original object names will be restored.
save(vector, vector2,file="data/vector2.Rdata")

# save.image() stores the whole current workspace.
# This is useful to know, but in reproducible analyses it is usually
# better to save scripts and selected objects explicitly.
save.image(file='data/myEnvironment.RData')

Data files in RData format can be opened from the Environment tab or with the load() function. To check that it was correctly loaded, we can remove it before loading with the rm() function.

# Remove the objects from the Global Environment in our RStudio session.
# This allows us to check whether load() really restores them.
rm(vector)
rm(vector2)

# load() restores the object names that were saved in the RData file.
# Notice that we do not choose new names here.
load("data/vector2.Rdata")

# Check that the objects are available again.
vector
[1] 1 2 3 4 5
vector2
 [1]  3  5  6  7  8  9 10 11 12 13
Caution

Note that if you save your data with save(), it cannot be restored under a different name. The original object names are automatically used. If you want to save one object and restore it with a different name, use the functions saveRDS() and readRDS().

2.6 Quick exercise (VII): save() or saveRDS()?

You want to save a single object called sm, and later load it under a different name, for example my_matrix.

Which pair of functions is most appropriate?

Select the right answer

# saveRDS() saves a single R object.
# Unlike save(), it does not force us to restore the object with its
# original name.
saveRDS(sm, file = "data/sm.rds")

# readRDS() returns the saved object, so we can assign it to any name.
# Here we deliberately use a new name.
my_matrix <- readRDS("data/sm.rds")

2.7 Quick exercise (VIII)

We are using the same directory tree. Your wd is HPBBM2022/data and you need to save a data frame named table1 as table1.csv in the folder HPBBM2023/data using ; as separator. How would you do it without changing the working directory? Try it also with your own computer.

Select the right answer

NoteInteractive data input & output in R

You will almost always import your working data from a file. However, especially if you are working with very small datasets, it is also possible to add your data interactively directly in the console, as you did in some of the examples before.

You can also define your objects and enter your data interactively using the scan() and readline() functions, as in the examples below. For output, you can simply call the object by its name or use the print() function, which displays the contents of the object on the screen. You can try the following code.1

# This chunk is not evaluated when the page is rendered because these
# functions require interactive input from the user.

# scan(n = 4) asks the user to enter exactly four values.
vector <- scan(n=4)

# scan() without n keeps reading values until the user stops input.
vector2 <- scan()

# readline() reads one line of text from the console.
str <- readline()

# Calling an object name prints the object.
vector

# print() makes the output explicit. This is useful inside functions
# or scripts where you want to control what is displayed.
print(vector2)
print(str)

# edit() opens an interactive editor for the object.
# This is useful to know, but it is not usually recommended in
# reproducible scripts because manual edits are not recorded as code.
edit(str)

Although seldom used, you can also edit the contents of your objects using the function edit(). This function can be used to edit different objects, including vectors, strings, matrices or data frames. macOS users may need to install XQuartz X11 tool.

3 Basic Data Management in R

Now we are going to import and explore an example dataset containing metadata from an Illumina sequencing project of pathogenic E. coli strains (Flament-Simon et al. 2020, https://doi.org/10.1038/s41598-020-69356-6). However, for didactic purposes, the original data have been simplified and manipulated and the attached datasets do not fully correspond to the actual data.

You can find the table in the data folder or download it here: coli_genomes.csv.

3.1 Open and explore a data frame

As you can see in the R help, the function read.table() has several default options, such as header = FALSE. When you have a spreadsheet export file where fields are divided by commas or semicolons, you can use read.csv() or read.csv2() instead of writing all the arguments manually in read.table().

For Spaniards, there is also read.csv2(), which uses a comma for the decimal point and a semicolon for the separator. These functions are wrappers of read.table() with custom default options. Likewise, there are write.csv() and write.csv2(), which are wrappers of write.table().

Before analysing a dataset, it is important to inspect it. A quick first exploration usually includes checking:

  • the first and last rows,
  • the number of rows and columns,
  • the variable names,
  • the type of each variable,
  • whether some values may need cleaning.

The following commands are a useful first checklist when opening a new table in R. They also illustrate several ways to open a table, including some common mistakes.

# Note differences between read.table(), read.csv() and read.csv2().

# Intentional mistake / incomplete import:
# read.table() assumes header = FALSE and uses whitespace as separator by default.
# Our file is semicolon-separated and has a header line, so the result will not
# be imported as intended.
coli_genomes <- read.table(file = "data/coli_genomes.csv")
Error in `scan()`:
! line 2 did not have 11 elements
head(coli_genomes)
Error:
! objeto 'coli_genomes' no encontrado
# Better: here we specify the separator, decimal character and header.
# This is the explicit read.table() version.
coli_genomes <- read.table(file = "data/coli_genomes.csv", sep=";", dec=".", header=TRUE)
head(coli_genomes)
   Strain    Biosample Year.of.isolation   Source Phylogroup Serotype Clonotype
1 LREC237 SAMN14278613                NA   Human           D  ONT:H28  CH23-331
2 LREC239 SAMN14278614              2010   Human           C O153:H19    CH4-25
3 LREC240 SAMN14278615              2008   Human          B1  O76:H30   CH29-38
4 LREC241 SAMN14278616                NA    Human          A  O78:H11   CH11-41
5 LREC242 SAMN14278617              2011 Porcine           A  ONT:HNM    CH7-54
6 LREC243 SAMN14278618              2007 Porcine           A   O9:H37    CH7-31
  Sequence.Type VF No..Plasmids kmer Contigs    N50 longest.contig..bp.
1         ST524 18            3  117     223 272287              662555
2          ST88 14            3  117     159 323172              760527
3         ST156 10            2   89     114 270767              738861
4          ST48  5            3  117     212 112160              285056
5         ST746  5            9   89     320  45936              128053
6        ST3011  7            3   93     158 106897              369508
  total.assembled.bp contigs...1kb
1            5341632            74
2            5415613            57
3            4875343            47
4            5167401           101
5            4858138           212
6            4638334            93
# Intentional mistake / wrong default for this file:
# read.csv() assumes comma-separated values. If the file actually uses semicolons,
# the table will not be split into the expected columns.
coli_genomes <- read.csv(file = "data/coli_genomes.csv")
head(coli_genomes)
  Strain.Biosample.Year.of.isolation.Source.Phylogroup.Serotype.Clonotype.Sequence.Type.VF.No..Plasmids.kmer.Contigs.N50.longest.contig..bp..total.assembled.bp.contigs...1kb
1                                                                               LREC237;SAMN14278613;NA;Human ;D;ONT:H28;CH23-331;ST524;18;3;117;223;272287;662555;5341632;74
2                                                                               LREC239;SAMN14278614;2010;Human ;C;O153:H19;CH4-25;ST88;14;3;117;159;323172;760527;5415613;57
3                                                                              LREC240;SAMN14278615;2008;Human ;B1;O76:H30;CH29-38;ST156;10;2;89;114;270767;738861;4875343;47
4                                                                                  LREC241;SAMN14278616;NA;Human;A;O78:H11;CH11-41;ST48;5;3;117;212;112160;285056;5167401;101
5                                                                               LREC242;SAMN14278617;2011;Porcine ;A;ONT:HNM;CH7-54;ST746;5;9;89;320;45936;128053;4858138;212
6                                                                               LREC243;SAMN14278618;2007;Porcine ;A;O9:H37;CH7-31;ST3011;7;3;93;158;106897;369508;4638334;93
# Better than the previous line: we still use read.csv(), but we manually set
# sep = ";". This shows that wrappers can be customised.
coli_genomes <- read.csv(file = "data/coli_genomes.csv", sep=";")
head(coli_genomes)
   Strain    Biosample Year.of.isolation   Source Phylogroup Serotype Clonotype
1 LREC237 SAMN14278613                NA   Human           D  ONT:H28  CH23-331
2 LREC239 SAMN14278614              2010   Human           C O153:H19    CH4-25
3 LREC240 SAMN14278615              2008   Human          B1  O76:H30   CH29-38
4 LREC241 SAMN14278616                NA    Human          A  O78:H11   CH11-41
5 LREC242 SAMN14278617              2011 Porcine           A  ONT:HNM    CH7-54
6 LREC243 SAMN14278618              2007 Porcine           A   O9:H37    CH7-31
  Sequence.Type VF No..Plasmids kmer Contigs    N50 longest.contig..bp.
1         ST524 18            3  117     223 272287              662555
2          ST88 14            3  117     159 323172              760527
3         ST156 10            2   89     114 270767              738861
4          ST48  5            3  117     212 112160              285056
5         ST746  5            9   89     320  45936              128053
6        ST3011  7            3   93     158 106897              369508
  total.assembled.bp contigs...1kb
1            5341632            74
2            5415613            57
3            4875343            47
4            5167401           101
5            4858138           212
6            4638334            93
# Most convenient option for this type of European-style CSV file:
# read.csv2() uses sep = ";" and dec = "," by default.
coli_genomes <- read.csv2(file = "data/coli_genomes.csv")
head(coli_genomes)
   Strain    Biosample Year.of.isolation   Source Phylogroup Serotype Clonotype
1 LREC237 SAMN14278613                NA   Human           D  ONT:H28  CH23-331
2 LREC239 SAMN14278614              2010   Human           C O153:H19    CH4-25
3 LREC240 SAMN14278615              2008   Human          B1  O76:H30   CH29-38
4 LREC241 SAMN14278616                NA    Human          A  O78:H11   CH11-41
5 LREC242 SAMN14278617              2011 Porcine           A  ONT:HNM    CH7-54
6 LREC243 SAMN14278618              2007 Porcine           A   O9:H37    CH7-31
  Sequence.Type VF No..Plasmids kmer Contigs    N50 longest.contig..bp.
1         ST524 18            3  117     223 272287              662555
2          ST88 14            3  117     159 323172              760527
3         ST156 10            2   89     114 270767              738861
4          ST48  5            3  117     212 112160              285056
5         ST746  5            9   89     320  45936              128053
6        ST3011  7            3   93     158 106897              369508
  total.assembled.bp contigs...1kb
1            5341632            74
2            5415613            57
3            4875343            47
4            5167401           101
5            4858138           212
6            4638334            93
# First inspection: show the beginning and the end of the data frame.
head(coli_genomes)
   Strain    Biosample Year.of.isolation   Source Phylogroup Serotype Clonotype
1 LREC237 SAMN14278613                NA   Human           D  ONT:H28  CH23-331
2 LREC239 SAMN14278614              2010   Human           C O153:H19    CH4-25
3 LREC240 SAMN14278615              2008   Human          B1  O76:H30   CH29-38
4 LREC241 SAMN14278616                NA    Human          A  O78:H11   CH11-41
5 LREC242 SAMN14278617              2011 Porcine           A  ONT:HNM    CH7-54
6 LREC243 SAMN14278618              2007 Porcine           A   O9:H37    CH7-31
  Sequence.Type VF No..Plasmids kmer Contigs    N50 longest.contig..bp.
1         ST524 18            3  117     223 272287              662555
2          ST88 14            3  117     159 323172              760527
3         ST156 10            2   89     114 270767              738861
4          ST48  5            3  117     212 112160              285056
5         ST746  5            9   89     320  45936              128053
6        ST3011  7            3   93     158 106897              369508
  total.assembled.bp contigs...1kb
1            5341632            74
2            5415613            57
3            4875343            47
4            5167401           101
5            4858138           212
6            4638334            93
tail(coli_genomes, n=2)
    Strain    Biosample Year.of.isolation Source Phylogroup Serotype Clonotype
24 LREC261 SAMN14278636              2016 Human           A  O98:H26   CH27-23
25 LREC262 SAMN14278637              2012 Human          B1  O66:H10    CH4-32
   Sequence.Type VF No..Plasmids kmer Contigs    N50 longest.contig..bp.
24        ST8233  2            4   89     114 187945              537848
25        ST1049  4            2  113      94 325747              822206
   total.assembled.bp contigs...1kb
24            4821342            53
25            4839344            32
# Indexing examples:
# row 1, all columns
coli_genomes[1,]
   Strain    Biosample Year.of.isolation Source Phylogroup Serotype Clonotype
1 LREC237 SAMN14278613                NA Human           D  ONT:H28  CH23-331
  Sequence.Type VF No..Plasmids kmer Contigs    N50 longest.contig..bp.
1         ST524 18            3  117     223 272287              662555
  total.assembled.bp contigs...1kb
1            5341632            74
# all rows, column 1
coli_genomes[,1]
 [1] "LREC237" "LREC239" "LREC240" "LREC241" "LREC242" "LREC243" "LREC244"
 [8] "LREC245" "LREC246" "LREC247" "LREC248" "LREC249" "LREC250" "LREC251"
[15] "LREC252" "LREC253" "LREC254" "LREC255" "LREC256" "LREC257" "LREC258"
[22] "LREC259" "LREC260" "LREC261" "LREC262"
# rows 1 to 6 and columns 2 to 4
coli_genomes[1:6,2:4]
     Biosample Year.of.isolation   Source
1 SAMN14278613                NA   Human 
2 SAMN14278614              2010   Human 
3 SAMN14278615              2008   Human 
4 SAMN14278616                NA    Human
5 SAMN14278617              2011 Porcine 
6 SAMN14278618              2007 Porcine 
# Basic dimensions of the data frame.
# dim() returns rows and columns.
dim(coli_genomes)
[1] 25 16
# For a data frame, length() returns the number of columns, not the number of rows.
# This is a common source of confusion.
length(coli_genomes)
[1] 16
# Explicit alternatives for columns and rows.
ncol(coli_genomes)
[1] 16
nrow(coli_genomes)
[1] 25
# Data frame structure in one line.
# str() is often the fastest way to detect wrong imports.
str(coli_genomes)
'data.frame':   25 obs. of  16 variables:
 $ Strain             : chr  "LREC237" "LREC239" "LREC240" "LREC241" ...
 $ Biosample          : chr  "SAMN14278613" "SAMN14278614" "SAMN14278615" "SAMN14278616" ...
 $ Year.of.isolation  : int  NA 2010 2008 NA 2011 2007 2006 2006 2010 2013 ...
 $ Source             : chr  "Human " "Human " "Human " "Human" ...
 $ Phylogroup         : chr  "D" "C" "B1" "A" ...
 $ Serotype           : chr  "ONT:H28" "O153:H19" "O76:H30" "O78:H11" ...
 $ Clonotype          : chr  "CH23-331" "CH4-25" "CH29-38" "CH11-41" ...
 $ Sequence.Type      : chr  "ST524" "ST88" "ST156" "ST48" ...
 $ VF                 : int  18 14 10 5 5 7 4 2 10 22 ...
 $ No..Plasmids       : int  3 3 2 3 9 3 7 7 1 4 ...
 $ kmer               : int  117 117 89 117 89 93 115 115 113 113 ...
 $ Contigs            : int  223 159 114 212 320 158 277 203 131 215 ...
 $ N50                : int  272287 323172 270767 112160 45936 106897 89185 94368 326769 248158 ...
 $ longest.contig..bp.: int  662555 760527 738861 285056 128053 369508 281444 280268 451887 504233 ...
 $ total.assembled.bp : int  5341632 5415613 4875343 5167401 4858138 4638334 5406295 4796593 5173794 5364777 ...
 $ contigs...1kb      : int  74 57 47 101 212 93 155 114 56 76 ...
# Type of data in selected variables.
# Notice that selecting a column with $ and selecting with [, ] may differ
# depending on whether the result is simplified to a vector or kept as a data frame.
typeof(coli_genomes$Strain)
[1] "character"
typeof(coli_genomes[,2])
[1] "character"
typeof(coli_genomes[,9])
[1] "integer"
# Column and row names.
names(coli_genomes)
 [1] "Strain"              "Biosample"           "Year.of.isolation"  
 [4] "Source"              "Phylogroup"          "Serotype"           
 [7] "Clonotype"           "Sequence.Type"       "VF"                 
[10] "No..Plasmids"        "kmer"                "Contigs"            
[13] "N50"                 "longest.contig..bp." "total.assembled.bp" 
[16] "contigs...1kb"      
colnames(coli_genomes)
 [1] "Strain"              "Biosample"           "Year.of.isolation"  
 [4] "Source"              "Phylogroup"          "Serotype"           
 [7] "Clonotype"           "Sequence.Type"       "VF"                 
[10] "No..Plasmids"        "kmer"                "Contigs"            
[13] "N50"                 "longest.contig..bp." "total.assembled.bp" 
[16] "contigs...1kb"      
rownames(coli_genomes)
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15"
[16] "16" "17" "18" "19" "20" "21" "22" "23" "24" "25"
# Three ways to rename the third variable are shown for comparison.
# The second option is usually the clearest when renaming one column.
names(coli_genomes[3]) <- 'Year'
names(coli_genomes)[3] <- 'Year'
colnames(coli_genomes[3]) <- 'Year'

3.2 Quick exercise (IX): exploring a data frame

You have imported a data frame called coli_genomes.

Which command shows the first rows of the data frame?

Select the right answer

Which command shows the number of rows and columns?

Select the right answer

Which command gives a compact summary of the structure of the data frame?

Select the right answer

Some of the columns include character data that may actually represent categorical variables, so we can encode them as factors. Using the function as.factor(), you can convert a character vector into a categorical variable.

# Some character variables actually represent categories.
# Converting them to factors helps R treat them as categorical variables.
coli_genomes$Source <- as.factor(coli_genomes$Source)
coli_genomes$Phylogroup <- as.factor(coli_genomes$Phylogroup)

# Check that the structure has changed.
str(coli_genomes) # data frame structure updated
'data.frame':   25 obs. of  16 variables:
 $ Strain             : chr  "LREC237" "LREC239" "LREC240" "LREC241" ...
 $ Biosample          : chr  "SAMN14278613" "SAMN14278614" "SAMN14278615" "SAMN14278616" ...
 $ Year               : int  NA 2010 2008 NA 2011 2007 2006 2006 2010 2013 ...
 $ Source             : Factor w/ 4 levels "Avian ","Human",..: 3 3 3 2 4 4 4 4 4 3 ...
 $ Phylogroup         : Factor w/ 4 levels "A","B1","C","D": 4 3 2 1 1 1 1 1 3 4 ...
 $ Serotype           : chr  "ONT:H28" "O153:H19" "O76:H30" "O78:H11" ...
 $ Clonotype          : chr  "CH23-331" "CH4-25" "CH29-38" "CH11-41" ...
 $ Sequence.Type      : chr  "ST524" "ST88" "ST156" "ST48" ...
 $ VF                 : int  18 14 10 5 5 7 4 2 10 22 ...
 $ No..Plasmids       : int  3 3 2 3 9 3 7 7 1 4 ...
 $ kmer               : int  117 117 89 117 89 93 115 115 113 113 ...
 $ Contigs            : int  223 159 114 212 320 158 277 203 131 215 ...
 $ N50                : int  272287 323172 270767 112160 45936 106897 89185 94368 326769 248158 ...
 $ longest.contig..bp.: int  662555 760527 738861 285056 128053 369508 281444 280268 451887 504233 ...
 $ total.assembled.bp : int  5341632 5415613 4875343 5167401 4858138 4638334 5406295 4796593 5173794 5364777 ...
 $ contigs...1kb      : int  74 57 47 101 212 93 155 114 56 76 ...

How many levels are there in Source? It is not uncommon to find mistakes in our data, usually made when the data were recorded. For example, a space may have been inserted before a value. By default, this white space will be kept in the R environment, so 'Human' will be recognised as a different value from ' Human'. To avoid this type of error, we can use the strip.white argument.

# unique() shows the different values found in the variable.
# Intentional data-cleaning issue: if one value has an extra leading or trailing
# space, R will treat it as a different category.
unique(coli_genomes$Source)
[1] Human    Human    Porcine  Avian   
Levels: Avian  Human Human  Porcine 
# table() counts how many observations belong to each category.
table(coli_genomes$Source)

  Avian     Human   Human  Porcine  
       3        1       16        5 
# Re-import the file using strip.white = TRUE.
# This removes leading/trailing spaces in unquoted character fields.
coli_genomes <- read.csv2(file = "data/coli_genomes.csv",  strip.white = TRUE)

# Convert again to factors after re-importing.
coli_genomes$Source <- as.factor(coli_genomes$Source)
coli_genomes$Phylogroup <- as.factor(coli_genomes$Phylogroup)

# Check whether the apparent extra categories disappeared.
unique(coli_genomes$Source)
[1] Human   Porcine Avian  
Levels: Avian Human Porcine

3.3 Quick exercise (X): complete the code

Complete the following code to import coli_genomes.csv from the data folder using read.csv2() and remove extra white spaces.

At this point, you may consider that writing the name of the data frame every time that you want to work with it can be repetitive. In fact, we don’t need to do it.

# attach() makes the columns of coli_genomes available by name.
# This allows us to write Source instead of coli_genomes$Source.
attach(coli_genomes) # attach

# This works because Source is now found in the attached data frame.
table(Source)
Source
  Avian   Human Porcine 
      3      17       5 
# Always detach when you finish, otherwise attached objects may remain
# in the search path and create confusing results later.
detach(coli_genomes)

Note that attach() can be used for any R object, including data frames, lists, vectors and packages. Once attached, R will consider those objects as databases, located in new, temporary environments.

WarningBe careful with attach()

The function attach() can make column names directly available, so you can write table(Source) instead of table(coli_genomes$Source). However, it can also make your code less explicit and may lead to confusion if different objects have variables with the same name.

For this reason, in most scripts it is safer to use the explicit form:

table(coli_genomes$Source)

rather than relying on attach().

TipThrow out the trash

If you want to remove some data to free up your computer’s memory, you can use the rm() function (aka remove()) to remove a specific object from your working environment. If you are running a script with large datasets, you can also use gc() to free memory after a large object has been removed. This is also done automatically without the user having to intervene, but it can be useful to call gc() after a large object has been removed, as this can prompt R to return memory to the operating system.

3.4 Renaming, changing and adding variables

We can also rename some variables to use easier names.

# First check all variable names.
# This helps us identify the position of the columns we want to rename.
names(coli_genomes) # see all variable names
 [1] "Strain"              "Biosample"           "Year.of.isolation"  
 [4] "Source"              "Phylogroup"          "Serotype"           
 [7] "Clonotype"           "Sequence.Type"       "VF"                 
[10] "No..Plasmids"        "kmer"                "Contigs"            
[13] "N50"                 "longest.contig..bp." "total.assembled.bp" 
[16] "contigs...1kb"      
# Rename variables by position.
# This is quick, but it requires being sure that the column order is correct.
names(coli_genomes)[3] <- 'Year'
names(coli_genomes)[10] <- 'Plasmids'
names(coli_genomes)[c(15,16)] <- c('Assembly_length','contigs1kb')

# Check that the new names were applied correctly.
names(coli_genomes)
 [1] "Strain"              "Biosample"           "Year"               
 [4] "Source"              "Phylogroup"          "Serotype"           
 [7] "Clonotype"           "Sequence.Type"       "VF"                 
[10] "Plasmids"            "kmer"                "Contigs"            
[13] "N50"                 "longest.contig..bp." "Assembly_length"    
[16] "contigs1kb"         

We are going to simplify our data frame by dropping one or more variables (columns):

# Show the data frame without column 12.
# Important: this line prints the modified view, but does not overwrite
# coli_genomes because we do not assign the result to an object.
coli_genomes[,-12]
    Strain    Biosample Year  Source Phylogroup Serotype  Clonotype
1  LREC237 SAMN14278613   NA   Human          D  ONT:H28   CH23-331
2  LREC239 SAMN14278614 2010   Human          C O153:H19     CH4-25
3  LREC240 SAMN14278615 2008   Human         B1  O76:H30    CH29-38
4  LREC241 SAMN14278616   NA   Human          A  O78:H11    CH11-41
5  LREC242 SAMN14278617 2011 Porcine          A  ONT:HNM     CH7-54
6  LREC243 SAMN14278618 2007 Porcine          A   O9:H37     CH7-31
7  LREC244 SAMN14278619 2006 Porcine          A   O2:H32    CH11-23
8  LREC245 SAMN14278620 2006 Porcine          A  ONT:H45    C11-398
9  LREC246 SAMN14278621 2010 Porcine          C   O8:H19     CH4-54
10 LREC247 SAMN14278622 2013   Human          D O145:H28   CH23-331
11 LREC248 SAMN14278623 2013   Human          A O123:H16     C11-94
12 LREC249 SAMN14278624 2013   Human          D O145:H28   CH23-331
13 LREC250 SAMN14278625 2013   Human          D O145:H28   CH23-331
14 LREC251 SAMN14278626 2013   Human          D O145:H28   CH23-331
15 LREC252 SAMN14278627 2013   Human          A  ONT:H37     C11-54
16 LREC253 SAMN14278628 2013   Avian          A  ONT:H19    CH94-23
17 LREC254 SAMN14278629 2011   Avian         B1 O142:H30     C41-35
18 LREC255 SAMN14278630 2005   Avian          C  O78:H19     CH4-27
19 LREC256 SAMN14278631 2012   Human          C   O8:H19     CH4-54
20 LREC257 SAMN14278632 2012   Human          C   O9:H19     CH4-27
21 LREC258 SAMN14278633 2012   Human          A    O9:H4     CH7-34
22 LREC259 SAMN14278634 2015   Human          C   O9:H19 CH4like-27
23 LREC260 SAMN14278635 2012   Human          A  ONT:H33    CH11-54
24 LREC261 SAMN14278636 2016   Human          A  O98:H26    CH27-23
25 LREC262 SAMN14278637 2012   Human         B1  O66:H10     CH4-32
   Sequence.Type VF Plasmids kmer    N50 longest.contig..bp. Assembly_length
1          ST524 18        3  117 272287              662555         5341632
2           ST88 14        3  117 323172              760527         5415613
3          ST156 10        2   89 270767              738861         4875343
4           ST48  5        3  117 112160              285056         5167401
5          ST746  5        9   89  45936              128053         4858138
6         ST3011  7        3   93 106897              369508         4638334
7           ST10  4        7  115  89185              281444         5406295
8        ST10888  2        7  115  94368              280268         4796593
9        ST10889 10        1  113 326769              451887         5173794
10         ST137 22        4  113 248158              504233         5364777
11       ST10850 10        4  113 241249              809158         5293420
12          ST32 22        1  115 200150              424527         5389075
13         ST137 22        3  111 281589              617142         5340478
14          ST32 20        1  113 182651              412836         5276782
15          ST48  1        0  113 105396              272304         4507328
16         ST347  2        0  117 110661              497785         4664768
17         ST359  9        4  113 240847              460510         4992565
18          ST88 11        4  113 405376             1190696         5196698
19          ST88 14        2  113 281822             1140163         5252065
20          ST88 14        4   91 140521              284241         5085107
21          ST46  8        4   85  86565              300086         4915667
22       ST10890 13        3  113 326962              749412         5200701
23          ST10  2        5  117 228491              576949         4881205
24        ST8233  2        4   89 187945              537848         4821342
25        ST1049  4        2  113 325747              822206         4839344
   contigs1kb
1          74
2          57
3          47
4         101
5         212
6          93
7         155
8         114
9          56
10         76
11         55
12        131
13         78
14         95
15         78
16         77
17         42
18         38
19         43
20        110
21        121
22         77
23         48
24         53
25         32
# This can also be used to remove rows (cases).
# Here we do assign the result back to coli_genomes, so rows 9 to 11
# are actually removed from the object.
coli_genomes <- coli_genomes[-c(9:11),]

We know the Assembly_length and the number of Contigs, but we would like to represent the average contig length.

# Create a new variable using existing columns.
# The $ operator selects or creates a column in a data frame.
coli_genomes$average_contig <- coli_genomes$Assembly_length / coli_genomes$Contigs
Note

If you need more tips on handling tables in R, such as sorting, subsetting, or quick data merging by common variable(s), see Lesson R6.

3.5 Dealing with NAs

Real datasets often contain missing values. In R, missing values are represented as NA, which means “not available”.

Missing values affect many calculations. For example, if a vector contains at least one NA, functions such as mean() will usually return NA unless we explicitly ask R to remove missing values.

Imagine we want to know the average year of sample isolation.

# Intentional issue: if Year contains at least one NA, mean() returns NA.
# This is not an error; it is R telling us that the result is unknown
# because some values are missing.
mean(coli_genomes$Year)
[1] NA

As you may have guessed, the NA output means that there are some missing values and the mean cannot be calculated directly. We can check that and omit the NA values.

# Check for NA values in the whole data frame.
# This returns a logical table with TRUE where values are missing.
is.na(coli_genomes)
   Strain Biosample  Year Source Phylogroup Serotype Clonotype Sequence.Type
1   FALSE     FALSE  TRUE  FALSE      FALSE    FALSE     FALSE         FALSE
2   FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
3   FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
4   FALSE     FALSE  TRUE  FALSE      FALSE    FALSE     FALSE         FALSE
5   FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
6   FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
7   FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
8   FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
12  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
13  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
14  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
15  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
16  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
17  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
18  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
19  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
20  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
21  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
22  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
23  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
24  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
25  FALSE     FALSE FALSE  FALSE      FALSE    FALSE     FALSE         FALSE
      VF Plasmids  kmer Contigs   N50 longest.contig..bp. Assembly_length
1  FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
2  FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
3  FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
4  FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
5  FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
6  FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
7  FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
8  FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
12 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
13 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
14 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
15 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
16 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
17 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
18 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
19 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
20 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
21 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
22 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
23 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
24 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
25 FALSE    FALSE FALSE   FALSE FALSE               FALSE           FALSE
   contigs1kb average_contig
1       FALSE          FALSE
2       FALSE          FALSE
3       FALSE          FALSE
4       FALSE          FALSE
5       FALSE          FALSE
6       FALSE          FALSE
7       FALSE          FALSE
8       FALSE          FALSE
12      FALSE          FALSE
13      FALSE          FALSE
14      FALSE          FALSE
15      FALSE          FALSE
16      FALSE          FALSE
17      FALSE          FALSE
18      FALSE          FALSE
19      FALSE          FALSE
20      FALSE          FALSE
21      FALSE          FALSE
22      FALSE          FALSE
23      FALSE          FALSE
24      FALSE          FALSE
25      FALSE          FALSE
# Count missing and non-missing values in the complete data frame.
table(is.na(coli_genomes))

FALSE  TRUE 
  372     2 
# Alternative: check complete rows.
# TRUE means that the row has no missing values.
# FALSE indicates an incomplete observation.
complete.cases(coli_genomes)
 [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
[13]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
# na.rm = TRUE tells mean() to remove missing values before calculating.
# This argument is common in many summary functions.
mean(coli_genomes$Year, na.rm=TRUE)
[1] 2011

What if we want to remove observations with an NA from the whole table?

# Create a new data frame without incomplete rows.
# Be careful: na.omit() removes any row with at least one NA in any column.
coli_genomes2 <- na.omit(coli_genomes)

# Now the mean can be calculated without na.rm = TRUE because the rows
# containing missing values have been removed.
mean(coli_genomes2$Year)
[1] 2011

In fact, you can use na.omit() for any object, either a vector, data frame or list.

3.6 Quick exercise (XI): missing values

You want to calculate the mean of the variable Year, ignoring missing values.

Which command is correct?

Select the right answer

Which command creates a new data frame without incomplete rows?

Select the right answer

Note that mean(na.omit(coli_genomes$Year)) would also work for the first question. However, na.rm = TRUE is the usual and most direct way to ignore missing values inside functions such as mean(). However, you should be careful with na.omit(coli_genomes), because it removes complete rows with missing values in any column.

3.7 Quick exercise (XII)

Now, we need to save the current version of coli_genomes in the data folder, using , as field separator.

Which of the following functions can you use to save the dataframe using , as field separator?

How would you do it?

Select the right answer

Finally, save the new dataset in your folder for future examples.

# Save the cleaned/modified table for future lessons.
# row.names = FALSE avoids writing row numbers as an extra first column.
write.csv(coli_genomes,"data/coli_genomes_renamed.csv", row.names=FALSE)

3.8 Quick exercise (XIII)

R has some built-in datasets that can be used as examples for plots or analysis. You can check all of them using the function data(). For the following exercise we are going to use one of those datasets, named quakes. You can import it as follows:

# data() loads built-in datasets available in R packages.
# Here we load the built-in quakes data frame.
data(quakes)

Then, use the function str() to examine the structure of the quakes dataset. Which of the following best describes the variables represented in this data frame?

Select the right answer

Now you need to create a new dataframe quakes2 with the three columns, lat, long and new_var, the latter being the product lat \(x\) long. What is the mean of the new variable? Fill the gaps to finish your code in the R snippet below.


4 References

  • An introduction to R, https://intro2r.com/work-d.html
  • R programming for data science, https://bookdown.org/rdpeng/rprogdatascience/
  • Using RStudio projects, https://support.rstudio.com/hc/en-us/articles/200526207
  • Importar y exportar datos en R, https://rsanchezs.gitbooks.io/rprogramming/content/chapter3/index.html
  • R in action. Robert I. Kabacoff. March 2022 ISBN 9781617296055
  • R para análisis científicos reproducibles. Software Carpentry Foundation. https://swcarpentry.github.io/r-novice-gapminder-es/

5 Review exercises

In this review exercise, you will import, inspect, debug and save a dataset related to E. coli genomes. The goal is not only to obtain the correct numerical results, but also to understand what can go wrong when importing and analysing data in R.

  1. Load the file colis3.csv as an object named colis.

  2. Explore the dataset using at least the following functions:

head()
tail()
dim()
names()
str()

Check whether the import worked as expected. In particular, answer the following questions:

  • Are the columns separated correctly?
  • Are numerical variables imported as numbers?
  • Are date-like variables imported as dates or as character strings?
  • Are there any unexpected column names or values?
  1. Check whether the following code works as expected. If it does not, explain the problem and correct it:
mean(colis$Year)
  1. Check whether the following code works as expected. If it does not, explain the problem and correct it:
mean(colis$seqs)
  1. The variable seqs contains sequencing dates. Convert it into a date object using as.Date() and check the structure of the dataset again.

  2. Calculate the mean of the following variables, ignoring missing values when necessary:

Year
AMR
Vir
CRISPR
Integron
  1. Create a small summary table containing the name of each variable and the corresponding mean value.

    The table should have at least two columns:

Variable
Mean
  1. Check how many missing values are present in each column of colis.

  2. Create a copy of the dataset named colis_no_na after removing incomplete observations.

  3. Compare the number of rows in colis and colis_no_na. How many rows were removed?

  4. Save colis and colis_no_na together in a single file named review_R3.RData.

  5. Save the summary table as review_R3_summary.csv in the data/ folder. Make sure that row names are not written as an extra column.

  6. Add short comments to your script explaining:

    • which lines import data,
    • which lines check the data structure,
    • which lines clean or transform data,
    • which lines calculate summary values,
    • which lines save results.

6 Extra (short) exercises

Want more? Try the input/output examples from Techvidvan website: https://techvidvan.com/tutorials/r-input-and-output-functions/

7 Session Info

sessionInfo()
R version 4.6.2 (2026-10-29 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 11 x64 (build 26200)

Matrix products: default
  LAPACK version 3.12.1

locale:
[1] LC_COLLATE=Spanish_Spain.utf8  LC_CTYPE=Spanish_Spain.utf8   
[3] LC_MONETARY=Spanish_Spain.utf8 LC_NUMERIC=C                  
[5] LC_TIME=Spanish_Spain.utf8    

time zone: Europe/Madrid
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] webexercises_1.1.0 formatR_1.14       knitr_1.51        

loaded via a namespace (and not attached):
 [1] digest_0.6.39     fastmap_1.2.0     xfun_0.57         glue_1.8.1       
 [5] htmltools_0.5.9   rmarkdown_2.31    lifecycle_1.0.5   cli_3.6.6        
 [9] vctrs_0.7.3       compiler_4.6.2    rstudioapi_0.19.0 tools_4.6.2      
[13] pillar_1.11.1     evaluate_1.0.5    yaml_2.3.12       otel_0.2.0       
[17] rlang_1.2.0       jsonlite_2.0.0    htmlwidgets_1.6.4
Back to top

Footnotes

  1. Since it is interactive, we cannot run it when we render the source file into a static web page. This can be prevented in Markdown/Quarto with the option eval: false in the chunk.↩︎

Modesto Redrejo Rodríguez & Luis del Peso, 2026