Skip to main content

Appendix A — A Beginner’s Guide to R

This appendix assumes no programming experience. Work through the sections in order, typing each example into a saved R script. All clinical data are synthetic. The examples use base R to minimize installation requirements. The companion folder examples/appendix-a/ contains the CSV, script and executable Quarto report. Run the examples from that folder.

A.1 Getting started

R is a language for expressing computations; RStudio is an optional interface for editing and running those computations. Install R from CRAN first, then install RStudio Desktop if desired. Open a new script, save it in a project folder, and run one line at a time. The console evaluates commands immediately; a script preserves the commands for later use. Avoid relying on objects created in a previous session.

R.version.string
getwd()
2 + 3 * 4

Interpretation. 14 is the result of the arithmetic expression because multiplication precedes addition. The other outputs depend on your installation.

TipGuided practice 1

Evaluate (2 + 3) * 4 and explain the difference.

A.2 Objects and arithmetic

Assignment stores a value under a name. Use descriptive names that indicate units. R is case sensitive. The assignment arrow is conventional, while equality comparison uses two equals signs. A numeric result does not automatically retain its physical units, so record them in the surrounding explanation.

dose_mg <- 80
volume_l <- 4
concentration <- dose_mg / volume_l
concentration
concentration == 20

Interpretation. 20 mg/L in this simplified arithmetic example, not a dosing recommendation.

TipGuided practice 2

Change the volume to 5 L and recompute.

A.3 Vectors and indexing

A vector stores values of one atomic type. Arithmetic generally operates element by element. Indexing begins at one. A logical index selects values satisfying a condition; a negative index excludes positions. Mixing text and numeric values in a vector can coerce all values to text.

wait <- c(10, 12, 15, 18, 25)
wait[2]
wait[wait > 15]
wait / 60

Interpretation. The second value is 12; values above 15 are 18 and 25. Division converts minutes to hours.

TipGuided practice 3

Select values at positions 1 and 5.

A.4 Types and missing values

Numeric, character and logical values serve different purposes. NA represents missing information rather than zero. Comparisons involving NA generally return NA. Report the number of missing observations before using na.rm; deletion may change the population represented by an analysis.

x <- c(8, 14, 11, 17, 10, NA)
class(x)
sum(is.na(x))
mean(x, na.rm = TRUE)

Interpretation. One value is missing; the observed mean is 12 minutes.

TipGuided practice 4

Calculate the observed sample size.

A.5 Sequences and mathematical functions

Use seq to construct a regular grid of input values and evaluate a mathematical function at each point. R trigonometric functions use radians. The natural logarithm is log, while exp is its inverse. A grid approximates a continuous curve rather than representing every possible input.

t <- seq(0, 10, by = 0.5)
C <- 80 * exp(-0.2 * t)
log(2) / 0.2
plot(t, C, type = "l", xlab = "Hours", ylab = "Concentration (units/L)")

Interpretation. The model half-life is approximately 3.466 hours.

TipGuided practice 5

Evaluate concentration at five hours.

A.6 Matrices and lists

A matrix is a rectangular array of a single atomic type. Matrix multiplication uses %%, not . Lists can contain objects of different types and lengths. These structures are useful for linear models, multivariable calculations, and collecting analysis results.

A <- matrix(c(2, 1, 1, 3), nrow = 2, byrow = TRUE)
b <- c(5, 7)
x <- solve(A, b)
A %*% x
result <- list(solution = x, matrix = A)
result$solution

Interpretation. The solution is (1.6, 1.8); multiplication reconstructs (5, 7).

TipGuided practice 6

Explain why A * A is not matrix multiplication.

A.7 Data frames and importing data

A data frame represents observations in rows and variables in columns. In the supplied example folder, clinic.csv contains synthetic appointments, not actual patient records. Read the file from the project directory and inspect its structure before analyzing it. Blank numeric fields are interpreted as missing by the explicit import settings.

clinic <- read.csv("clinic.csv", na.strings = c("", "NA"))
str(clinic)
head(clinic)
stopifnot(!anyDuplicated(clinic$id))
summary(clinic)

Interpretation. There are 11 rows, five columns and one missing waiting time.

TipGuided practice 7

Extract the sleep column and calculate its mean.

A.8 Filtering and transforming

Filtering selects observations, while transformation creates or changes variables. Keep the original data intact and assign derived results to new objects. Logical conditions can be combined with & and |. Always consider missing values in selection rules.

a <- subset(clinic, clinic == "A")
clinic$wait_hours <- clinic$wait / 60
long <- subset(clinic, !is.na(wait) & wait > 15)
nrow(long)

Interpretation. Three observed appointments exceed 15 minutes.

TipGuided practice 8

Select clinic B appointments with observed waits.

A.9 Descriptive statistics

The mean uses all observed values, while the median is resistant to extreme values. The sample standard deviation uses n minus one in the denominator. A summary should identify the units, sample size, and missing observations. Do not compare group means without considering study design and variability.

w <- clinic$wait
c(n = sum(!is.na(w)), mean = mean(w, na.rm = TRUE),
  median = median(w, na.rm = TRUE), sd = sd(w, na.rm = TRUE))
aggregate(wait ~ clinic, data = clinic, FUN = mean)

Interpretation. The pooled observed mean is 14 minutes; clinic means are 16 and 12 minutes.

TipGuided practice 9

Compute the observed range.

A.10 Graphics

A histogram shows the distribution of a quantitative variable; a boxplot summarizes location and spread; a scatterplot displays paired observations. Label axes with units and choose scales that do not exaggerate differences. Small samples benefit from displaying individual observations.

stripchart(wait ~ clinic, data = clinic, vertical = TRUE,
  method = "jitter", pch = 19, xlab = "Clinic", ylab = "Wait (minutes)")
plot(clinic$sleep, clinic$sbp, xlab = "Sleep (hours)",
  ylab = "Systolic BP (mmHg)", pch = 19)

Interpretation. The scatterplot illustrates a negative association in this constructed dataset, not a causal conclusion.

TipGuided practice 10

Create a histogram of observed waits.

Observed waiting times by clinic; diamonds indicate group means.

Observed waiting times by clinic; diamonds indicate group means.

A.11 Functions and control flow

A function packages a calculation under a meaningful name. Arguments are inputs and the last evaluated expression is normally returned. Validate inputs when a mathematical formula has a restricted domain. Use loops for repeated operations and vectorization when it makes the calculation clearer.

half_life <- function(k) {
  stopifnot(is.numeric(k), length(k) == 1, is.finite(k), k > 0)
  log(2) / k
}
sapply(c(0.1, 0.2, 0.4), half_life)

Interpretation. Half-lives are approximately 6.931, 3.466 and 1.733 hours.

TipGuided practice 11

What happens when k is zero?

A.12 Probability and simulation

R provides distribution functions with prefixes d, p, q and r for density or mass, cumulative probability, quantiles and random generation. A random seed makes a simulation repeatable in a compatible environment. Simulation estimates fluctuate and should not be confused with exact probabilities.

pnorm(26, mean = 20, sd = 6, lower.tail = FALSE)
set.seed(2026)
means <- replicate(2000, mean(rnorm(25, 20, 6)))
sd(means)
6 / sqrt(25)

Interpretation. The exact tail probability is about 0.1587; the simulated standard error should be near 1.2.

TipGuided practice 12

Repeat with sample size 100.

A.13 Inference and modeling

A confidence interval expresses sampling uncertainty under assumptions. Welch’s t procedure compares two independent group means without requiring equal variances. A regression describes a conditional mean relationship. These synthetic observations are for practice; no real clinical claim is justified.

t.test(wait ~ clinic, data = clinic)
fit <- lm(sbp ~ sleep, data = clinic)
summary(fit)
confint(fit)

Interpretation. Inspect the estimated difference and uncertainty; the formula orders groups A then B. The regression slope has units mmHg per hour.

TipGuided practice 13

Reverse the group order and explain the effect.

A.14 Packages and reproducibility

Install packages once into a library, then load them in each session where needed. Base R is sufficient for this appendix. For larger projects, record dependencies and consider renv to lock package versions. Never put installation commands in routinely executed report chunks.

sessionInfo()
# install.packages("ggplot2")
# library(ggplot2)
# renv::init()
# renv::snapshot()

Interpretation. sessionInfo records R and platform details. Commented lines are optional setup instructions.

TipGuided practice 14

Why should package installation be separated from rendering?

A.15 R inside Quarto

Create a file named report.qmd in the same directory as the CSV. Unlike the display-only examples above, an executable chunk uses braces around the language name. Quarto runs the chunk through knitr and inserts its output into the rendered publication. Render from a clean session to detect undeclared dependencies.

---
title: "Clinic waiting times"
format: html
engine: knitr
---

```{r}
#| label: load-data
clinic <- read.csv("clinic.csv", na.strings = c("", "NA"))
```

The observed mean waiting time is `r mean(clinic$wait, na.rm = TRUE)` minutes.

```{r}
#| label: fig-wait
#| fig-cap: "Observed waiting times by clinic."
stripchart(wait ~ clinic, data = clinic, vertical = TRUE, pch = 19)
```

Use quarto render report.qmd from the terminal. In RStudio, the Render button provides another route. echo: false hides code but retains results; include: false hides both. Neither option is a security boundary: never include private data or secrets in a public project.

A.16 Applied project: A reproducible clinic summary

Create a report that identifies the observational unit, documents missing values, compares waiting times across clinics, and investigates the relationship between sleep and systolic blood pressure. Include a table, two labeled figures, a discussion of limitations, and session information. Submit the QMD source, CSV and rendered HTML. Do not infer treatment effects from these constructed data.

Criterion Points
Data import and validation 5
Correct descriptive analysis 5
Appropriate graphics 5
Interpretation and limitations 5
Reproducible Quarto source 5

A.17 Further reading