1  Introduction to R

1.1 Prerequisites

Answer the following questions to see if you can bypass this chapter. You can find the answers at the end of the chapter in Section 1.14.

  1. What is the difference between c(1, 'a') and list(1, 'a')?
  2. In the expression df[df$x > 0, ], what kind of R object is df$x > 0, and what rule does R use to combine it with the comma to select rows?
  3. Predict the output of x <- 1:5; x[-1], x[c(TRUE, FALSE)], and x[[1]]. Which of these produces something that is not a numeric vector of length less than 5?

1.2 Learning objectives

By the end of this chapter you should be able to:

  • Install R and RStudio and configure a sensible working environment.
  • Read the R documentation system (?, ??, help()).
  • Distinguish between atomic vectors, lists, and the major data structures built on them.
  • Subset and mutate data with base R and with dplyr.
  • Write vectorized expressions and explain why they outperform equivalent for loops.

1.3 Orientation

R is the lingua franca of statistical computing in academic biostatistics. It is not the fastest language, nor the most elegant. It does, however, have by far the richest library of statistical methods. It also has the largest community of statisticians reading, writing, and reviewing code. Our aim in this chapter is to make the reader fluent enough in R to read the rest of the book.

We begin with the decisions that remain with the statistician, and then turn to installation and the organization of an R session. We then cover atomic vectors and coercion, subsetting, and vectorization. The chapter closes with the essentials of the tidyverse and a set of prompts for working with an LLM.

1.4 The statistician’s contribution

Large language models can produce passable R code for almost any introductory task. We shall see, however, that three decisions still require the judgment of the statistician.

1. Type discipline. R coerces silently between types in ways that can hide errors. c(1, '2') becomes c('1', '2') (character); TRUE + 1 becomes 2 (double). An LLM will happily accept whatever types flow through its generated code. It is therefore necessary for you to decide, before any computation runs, which types the data should carry. Where it matters, you should assert them with stopifnot(is.numeric(x)).

2. Base R vs tidyverse framing. The same transformation can be expressed in base R and in dplyr. An LLM will lean toward whichever style dominated its training data, which is usually dplyr for interactive work. The tradeoffs in performance, dependencies, and readability belong to you, and the needs of the project should settle them.

3. Edge cases in statistical data. R’s built-in functions handle NA, NaN, Inf, zero-length vectors, and length-mismatched vectors in different ways. The defaults are usually right for general-purpose data. Unfortunately, they are often wrong for biomedical data, where missingness is informative. An LLM will not check whether your data have the edge cases that would break its generated code, and so that check falls to you.

1.5 Installing R and RStudio

R is a free and open-source implementation of the S programming language. The base R installer may be downloaded from the Comprehensive R Archive Network (CRAN). Posit’s RStudio Desktop, a free integrated development environment, is available at https://posit.co/download/rstudio-desktop/. Install R first, then RStudio.

On macOS, the rig command-line tool (https://github.com/r-lib/rig) lets you install and switch between R versions cleanly:

brew install --cask rig
rig add release        # installs the current stable R
rig default release

We then verify the installation:

R --version
# R version 4.5.3 (2026-02-28) -- 'Single Candle'

When RStudio is launched, its default four-pane layout provides a script editor, a console, an environment inspector, and a files/plots/help browser.

1.6 The R console, scripts, and projects

An R session is anchored to a working directory and a set of loaded packages. Two conventions make sessions reproducible.

Use RStudio projects. A .Rproj file tells RStudio that the enclosing directory is a project. Opening the file sets the working directory automatically and isolates the session from the rest of your filesystem. We recommend that you always work inside a project, never from a stray session rooted in ~/.

Prefer scripts over the console. The console is for quick exploration, and scripts are for work that must be reproducible. A script is a .R or .qmd file that you can rerun from top to bottom to obtain the same result. Analyses that live only in the console history are lost when the session ends.

The .Rprofile file in a project runs automatically when you open a session. It is the natural place to set session-wide options, such as the CRAN mirror or the preferred number of significant digits. The renv package extends this pattern to pin package versions. Package and environment management is covered in detail in the practicum companion volume.

1.7 Atomic vectors and coercion

Everything in R is built from vectors. Even a single number like 5 is a vector of length 1.

R has six atomic types: logical, integer, double, character, complex, and raw. The last two are rarely used in statistical work. All elements of an atomic vector share a type. When we combine mixed types, R silently coerces them to the most general type in the chain logical → integer → double → character.

c(TRUE, 1L)         # -> integer: 1, 1
c(TRUE, 1L, 2.5)    # -> double:  1.0, 1.0, 2.5
c(TRUE, 1L, 'x')    # -> character: 'TRUE', '1', 'x'

Silent coercion is a common source of bugs. To illustrate, sum(c(1, 2, NA)) returns NA, not 3. Similarly, mean(c(TRUE, FALSE, TRUE)) returns 0.667 because the logicals coerce to c(1, 0, 1). That result is numerically correct and often useful, but it can surprise readers.

Lists differ from atomic vectors in that their elements can each carry a different type:

list(1, 'a', TRUE)    # length-3 list, three distinct types

Operations that work on atomic vectors often do not work on lists. When iterating over list elements, the appropriate tools are lapply(), sapply(), or purrr::map_*() (Chapter 4).

Special values:

  • NA is missing data. Most operations involving NA return NA.
  • NULL is the absence of an object. Assigning NULL to a list element removes it.
  • NaN is ‘not a number’ (for example, 0/0).
  • Inf and -Inf are the signed infinities (for example, 1/0).

Q: What does c(1, 'a') return, and why?

A: The character vector c('1', 'a'). R cannot store 1 and 'a' in the same atomic vector, so it coerces both to the most general type (character). To keep the original types, use list(1, 'a').

1.8 Subsetting: [, [[, and $

R offers three subsetting operators and four kinds of indices. Confusion between them is the most common source of errors in a first R course.

The three operators.

  • [ returns a subset of the same type as the original. For an atomic vector it returns a vector; for a list it returns a list; for a data frame it returns a data frame.
  • [[ returns a single element, stripping the container. From a list, [[ gives you the element itself (which might be any type); from an atomic vector, [[ returns a length-1 atomic of the same type.
  • $name is shorthand for [['name']] on a list or data frame.

The four index types.

x <- c(10, 20, 30, 40, 50)

x[2]              # positive integer: 20
x[c(1, 3, 5)]     # vector of positive integers: 10, 30, 50
x[-1]             # negative integer: drop element 1 -> 20, 30, 40, 50
x[x > 25]         # logical: 30, 40, 50
x[c('a', 'b')]    # character: works only if x has names

For data frames, [row, col] applies the subsetting rules along both dimensions. The expression df[df$x > 0, ] uses a logical row index (df$x > 0) to keep the rows where x is positive. The missing column index keeps all columns.

df <- data.frame(
  id  = 1:5,
  x   = c(3, -1, 5, 0, 8),
  grp = c('a', 'b', 'a', 'b', 'a')
)

df[df$x > 0, ]        # rows where x is positive
df[df$grp == 'a', ]   # rows in group 'a'
df[, c('id', 'x')]    # two columns, all rows

We note that a logical index built from a column containing NA produces NA rows rather than dropping those rows, a behavior that surprises many users. If you want the NA rows dropped, use which() or subset().

1.9 Vectorization

Vectorization means applying an operation to every element of a vector at once, without an explicit loop. It is the central design principle of R, and nearly every built-in function is vectorized.

x <- c(1, 2, 3, 4, 5)
x + 10                # 11 12 13 14 15, elementwise
x^2                   # 1 4 9 16 25
sqrt(x)               # 1.00 1.41 1.73 2.00 2.24

When two vectors of different lengths combine, R recycles the shorter vector to match the longer:

c(1, 2, 3, 4) + c(10, 20)    # 11 22 13 24  (recycled)

On the one hand, recycling without warning is convenient for scalar + vector arithmetic. On the other, it is dangerous when lengths mismatch by accident. R warns if the longer length is not a multiple of the shorter, but not otherwise.

Loop vs vectorized. The following benchmark compares the two on the same computation:

library(bench)

vectorised_zscore <- function(x) (x - mean(x)) / sd(x)

loop_zscore <- function(x) {
  z <- numeric(length(x))
  m <- mean(x)
  s <- sd(x)
  for (i in seq_along(x)) z[i] <- (x[i] - m) / s
  z
}

bench::mark(
  vectorised = vectorised_zscore(iris$Sepal.Length),
  loop       = loop_zscore(iris$Sepal.Length),
  iterations = 100
)

The vectorized version is faster because the elementwise arithmetic happens in compiled C code, not in R’s interpreter. The size of the gap depends on the R version, the hardware, and the length of the vector. On one recent laptop running R 4.6, the vectorized version was roughly twice as fast for the 150 values of iris$Sepal.Length. For a vector of length 1 million it was roughly ten times as fast. R’s byte-code compiler has narrowed the gap considerably for simple loops of this kind.

Q: Why is vectorized R code faster than an equivalent for loop that does the same arithmetic?

A: The vectorized operation hands the whole vector to a compiled C routine, which runs the loop internally at native speed. An R-level for loop invokes the R interpreter once per element, and the interpreter overhead dominates the actual arithmetic for simple operations.

Not every algorithm vectorizes. Sequential updates (MCMC chains, sequential hypothesis tests, change-point detection) require each step to depend on the previous one. Such updates cannot be written as single elementwise expressions. For these cases, Rcpp (Chapter 3) lets us write a C++ loop that R calls as a single function.

1.10 Tidyverse essentials

The tidyverse is a coordinated set of packages (dplyr, tidyr, ggplot2, purrr, and others) that share a common grammar for data manipulation and visualization. The dplyr package provides six core verbs and a pipe operator that chains them.

The native R pipe |> (introduced in R 4.1, 2021) passes its left-hand side as the first argument to the right-hand side:

x |> mean()          # same as mean(x)
x |> round(digits = 2)  # same as round(x, digits = 2)

Earlier tidyverse code uses the magrittr pipe %>%. The two are similar, and this book uses the native pipe exclusively.

The six dplyr verbs apply to data frames:

Verb Action
filter(df, condition) Keep rows where condition is TRUE
select(df, cols) Keep or drop columns
mutate(df, new = ...) Add or modify columns
summarise(df, ...) Reduce to a single row (or one per group)
arrange(df, col) Sort rows
group_by(df, col) Group for later verbs

To illustrate, consider a typical pipeline:

library(dplyr)

ChickWeight |>
  filter(Time <= 14) |>
  group_by(Diet, Time) |>
  summarise(
    mean_weight = mean(weight),
    n           = n(),
    .groups     = 'drop'
  ) |>
  arrange(Diet, Time)

The pipe reads from top to bottom like an analysis plan. We start with ChickWeight, keep the first 14 days, group by diet and day, summarize, and sort. The same computation in base R would fragment into intermediate variables and nested function calls. The pipe, by contrast, keeps the data flow visible.

Q: What does df |> group_by(x) |> summarise(m = mean(y)) return that summarise(df, m = mean(y)) does not?

A: A data frame with one row per distinct level of x, giving the mean of y within each group. Without group_by(), the second form collapses the whole data frame to a single row.

1.11 Collaborating with an LLM on R essentials

In Section 1.4 we named three decisions that require the judgment of the statistician. The prompts below exercise each one. As elsewhere in the book, the reader should treat the response of the LLM as a hypothesis to verify.

1.11.1 Type coercion

Prompt. ‘Read this CSV and compute the mean of the dose column’, then paste a CSV whose dose column mixes numeric strings and the literal string 'NA'.

What to watch for. read.csv() treats 'NA' strings as the missing sentinel by default, but readr::read_csv() has different defaults depending on version. A dose column with mixed content can silently come in as character. In that case mean() on the character vector returns NA with a warning. An LLM may also wrap the read in as.numeric() without warning you that values that fail to parse become NA.

Verification. Inspect str(df$dose) after the read. Confirm that the type is numeric and that the count of NA values matches the count of non-parseable source strings.

1.11.2 Base R vs tidyverse

Prompt. ‘Write R code to compute, for each level of a grouping variable, the mean of another variable, dropping missing values.’

What to watch for. An LLM will usually produce the dplyr form (group_by + summarise(mean(x, na.rm = TRUE))). It may not ask whether the project uses the tidyverse at all. Production R code in some settings runs on base R or data.table and imports no tidyverse. Examples include pharma, legacy packages, and FDA submissions via pharmaverse internals.

Verification. Confirm the dependency policy of the project before accepting the suggestion. If the tidyverse is permitted, keep the code from the LLM. If not, ask for the base R equivalent (aggregate(y ~ group, data = df, FUN = mean)) or the data.table equivalent.

1.11.3 Edge cases

Prompt. ‘Write a function that computes the ratio of two columns in a data frame.’

What to watch for. An LLM will typically write df$x / df$y without handling the cases that make the ratio undefined. These are zero denominators (which produce Inf), negative denominators (which change the sign), NA inputs (which propagate), and zero-row inputs (which return a zero-length numeric). In a biomedical analysis each case signals a real data phenomenon. A zero divisor may be a structural zero, a missing value may be a censored measurement, and so on.

Verification. Ask the LLM to list the inputs on which the function would produce unexpected output. Then extend the function to raise an error (with an explanatory message) in cases that indicate broken data, instead of silently returning Inf or NaN.

1.12 Exercises

  1. Write a function summarise_numeric(df) that takes a data frame and returns a data frame with one row per numeric column giving its mean, median, SD, and number of missing values. Do not use any package outside base R.
  2. Repeat exercise 1 using dplyr::summarise() across all numeric columns. Compare the two implementations for readability and speed.
  3. Explain, in at most three sentences, why sum(c(1, 2, NA)) == NA returns NA rather than TRUE.

1.13 Further reading

  • (Wickham et al., 2023), the canonical first book for R data analysis; the 2nd edition uses the native pipe throughout.
  • (Wickham, 2019) Chapters 1-3, essential for reading other people’s R code.
  • (Grolemund & Wickham, 2017), the 1st edition is still a readable slower-paced introduction to the tidyverse.

1.14 Prerequisites answers

  1. c(1, 'a') coerces both elements to the most permissive atomic type, producing c('1', 'a') (character). list(1, 'a') preserves the types of each element because lists are not atomic.
  2. df$x > 0 is a logical vector of length nrow(df). R applies logical subsetting along the first dimension of the data frame so that df[df$x > 0, ] keeps only the rows where the logical vector is TRUE. Rows where df$x > 0 is NA are returned as rows of all NA.
  3. x[-1] drops the first element and returns 2:5. x[c(TRUE, FALSE)] recycles the logical vector to length 5 and returns c(1, 3, 5). x[[1]] returns the scalar 1, which is still a length-1 numeric vector; the [[ ]] form is important conceptually (it strips list/vector structure) but on atomic vectors it behaves like [ ] with a single index. All three results are numeric vectors of length less than 5.