Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

This appendix is a lookup table, not a tutorial. Use it to install R and the course packages once, to find the one-line syntax for reading a course dataset, and to look up any R function you saw in a chapter but forgot how it works. Functions are grouped by the chapter that introduces them; a function used again in a later chapter is not repeated, so if you cannot find something under “your” chapter, check an earlier one.

Installing R for this course

The course was built and checked against R 4.6.0. Download it from CRAN for your operating system, then install RStudio Desktop as your editor; it is not required, but it makes running the chapter code much easier.

Every dataset in this book loads with base R alone (read.csv), but several chapters use add-on packages for diagnostics, model selection, and shrinkage. Install all of them once, before you start Chapter 2:

install.packages(c(
  "faraway", "car", "leaps", "lmtest", "ggplot2", "broom",
  "glmnet", "ellipse", "dplyr", "MASS", "boot", "carData", "HistData"
))

MASS and boot ship with R itself, so install.packages will report they are already present; the line above is safe to run regardless. Load a package in any R session with library(packagename) before using its functions; the chapter tables below note which package each function comes from when it is not base R.

Reading course data

Every dataset used in this book lives in data/ as a plain CSV, one row per observation, with column headers already set to the names used in the chapters. Read any of them with base R’s read.csv, giving the path relative to the book’s root folder:

toluca <- read.csv("data/toluca.csv")
head(toluca)
  lotsize hours
1      80   399
2      30   121
3      50   221
4      90   376
5      70   361
6      60   224

All chapter R code assumes your working directory is the book’s root folder (the one that contains data/), so every read.csv call in the book uses a path like "data/toluca.csv", never a full file-system path. In RStudio, open the project at the book root, or set it by hand with setwd("path/to/book-myst") before running any chapter’s code. See Appendix E: The Datasets of This Book for the story, provenance, and variable list of every dataset.

How to read the tables below

Each row gives the function, the package it comes from (blank means base R, already loaded in any session), a one-line description of what it does, and a minimal example. Functions are listed once, in the chapter where the book first uses them; later chapters build on these without repeating the entry. library(...) itself is not tabulated; load whichever package a function’s row names before calling it.

Chapter 1: Regression as a way of thinking

FunctionPackagePurposeExample
read.csvbaseRead a CSV file into a data frame.d <- read.csv("data/toluca.csv")
lmbaseFit a linear model by least squares.fit <- lm(hours ~ lotsize, data = d)
coefbaseExtract fitted coefficients from a model.coef(fit)
predictbaseCompute fitted or predicted values from a model.predict(fit)
meanbaseArithmetic mean of a vector.mean(d$hours)
minbaseSmallest value in a vector.min(d$lotsize)
sumbaseSum of a vector’s entries.sum(d$hours)
nrowbaseNumber of rows in a data frame.nrow(d)
corbasePearson correlation between two vectors.cor(d$lotsize, d$hours)
varbaseSample variance of a vector.var(d$hours)
sapplybaseApply a function to each element of a list or vector, simplifying the result.sapply(d, class)
roundbaseRound a number to a given number of decimal places.round(3.14159, 2)
plotbaseDraw a scatterplot or other base-R plot.plot(d$lotsize, d$hours)
ablinebaseAdd a straight line to an existing plot.abline(fit)
parbaseGet or set plotting parameters (layout, margins).par(mfrow = c(1, 2))
data.framebaseBuild a data frame from named vectors.data.frame(x = 1:3, y = 4:6)

Chapter 2: Simple linear regression

FunctionPackagePurposeExample
residualsbaseExtract residuals ei=YiY^ie_i = Y_i - \hat{Y}_i from a fitted model.residuals(fit)
fittedbaseExtract fitted values Y^i\hat{Y}_i from a fitted model.fitted(fit)
summarybasePrint a model’s coefficients, standard errors, tt tests, and R2R^2.summary(fit)
sqrtbaseSquare root.sqrt(25)
set.seedbaseFix the random-number generator’s starting point for reproducibility.set.seed(4210)
replicatebaseRepeat an expression a fixed number of times, collecting the results.replicate(1000, mean(rnorm(10)))
rnormbaseDraw random values from a Normal distribution.rnorm(10, mean = 0, sd = 1)
sdbaseSample standard deviation of a vector.sd(d$hours)

Chapter 3: Inference for simple linear regression

FunctionPackagePurposeExample
confintbaseConfidence intervals for a model’s coefficients.confint(fit, level = 0.95)
anovabaseAnalysis-of-variance table for a fitted model.anova(fit)
qtbaseQuantile (inverse CDF) of the tt distribution.qt(0.975, df = 23)
qfbaseQuantile (inverse CDF) of the FF distribution.qf(0.95, df1 = 1, df2 = 23)

Chapter 4: Correlation

FunctionPackagePurposeExample
cor.testbaseHypothesis test and confidence interval for a correlation.cor.test(d$lotsize, d$hours)
atanhbaseInverse hyperbolic tangent; the Fisher zz transform of a correlation.atanh(0.86)
tanhbaseHyperbolic tangent; inverts the Fisher zz transform.tanh(1.29)
qnormbaseQuantile (inverse CDF) of the standard Normal distribution.qnorm(0.975)
aggregatebaseCompute a summary statistic for each group in a data frame.aggregate(hours ~ lotsize, data = d, FUN = mean)
which.maxbaseIndex of the largest value in a vector.which.max(d$hours)

Chapter 5: Randomization and bootstrap inference for regression

FunctionPackagePurposeExample
samplebaseDraw a random sample (with or without replacement) from a vector.sample(d$hours, size = 25, replace = TRUE)
numericbaseCreate a numeric vector of a given length, filled with zeros.numeric(1000)
quantilebaseSample quantiles of a vector (used for bootstrap percentile intervals).quantile(boot_slopes, c(0.025, 0.975))
absbaseAbsolute value.abs(-3.5)
maxbaseLargest value in a vector.max(d$hours)
lengthbaseNumber of elements in a vector.length(d$hours)
cbaseCombine values into a vector.c(1, 2, 3)

Chapter 6: Matrix algebra for regression

FunctionPackagePurposeExample
dimbaseDimensions (rows, columns) of a matrix or data frame.dim(X)
headbaseFirst few rows of a data frame or matrix.head(d)
ncolbaseNumber of columns in a matrix or data frame.ncol(X)
cbindbaseBind vectors or matrices together as columns.X <- cbind(1, d$lotsize)
colnamesbaseGet or set a matrix’s column names.colnames(X) <- c("intercept", "lotsize")
matrixbaseBuild a matrix from a vector, given its dimensions.matrix(1:6, nrow = 2)
tbaseTranspose a matrix.t(X)
%*%baseMatrix multiplication.t(X) %*% X
isSymmetricbaseTest whether a matrix equals its own transpose.isSymmetric(t(X) %*% X)
qrbaseQR decomposition of a matrix (used internally by lm, and for rank checks).qr(X)$rank
detbaseDeterminant of a square matrix.det(t(X) %*% X)
solvebaseMatrix inverse, or solve a linear system Ax=b\mathbf{A}\mathbf{x} = \mathbf{b}.solve(t(X) %*% X)
diagbaseExtract or construct a diagonal matrix.diag(3)
as.numericbaseCoerce an object to a plain numeric vector.as.numeric(coef(fit))
cholbaseCholesky decomposition of a symmetric positive-definite matrix.chol(t(X) %*% X)
covbaseSample covariance matrix of a data frame or matrix.cov(d)

Chapter 7: The general linear model

FunctionPackagePurposeExample
all.equalbaseTest near-equality of two numeric objects, up to rounding error.all.equal(coef(fit), b_hand)

Chapter 8: Multiple regression in practice

FunctionPackagePurposeExample
residbaseExtract residuals from a fitted model (identical to residuals).resid(fit)
scalebaseCenter and/or scale the columns of a matrix or data frame.scale(d[, c("triceps", "thigh")])
as.data.framebaseCoerce an object (e.g. a matrix) to a data frame.as.data.frame(scale(d))
deviancebaseResidual sum of squares of a fitted model.deviance(fit)

Chapter 9: Model diagnostics

FunctionPackagePurposeExample
hatvaluesbaseLeverage values hiih_{ii}, the diagonal of the hat matrix.hatvalues(fit)
rstandardbaseStandardized (internally studentized) residuals.rstandard(fit)
rstudentbaseStudentized deleted (externally studentized) residuals.rstudent(fit)
cooks.distancebaseCook’s distance, an overall influence measure for each observation.cooks.distance(fit)
dffitsbaseDFFITS, the standardized change in a fitted value when one case is deleted.dffits(fit)
dfbetasbaseDFBETAS, the standardized change in each coefficient when one case is deleted.dfbetas(fit)
factorbaseConvert a variable to a categorical factor.d$grp <- factor(d$grp)
bptestlmtestBreusch-Pagan test for nonconstant error variance.bptest(fit)
shapiro.testbaseShapiro-Wilk test for Normality of a sample.shapiro.test(residuals(fit))
dwtestlmtestDurbin-Watson test for autocorrelated residuals.dwtest(fit)
librarybaseLoad an installed package into the current session.library(lmtest)
sortbaseSort a vector in increasing (or decreasing) order.sort(cooks.distance(fit))
whichbaseIndices of the TRUE entries of a logical vector.which(hatvalues(fit) > 0.5)
rangebaseMinimum and maximum of a vector, as a length-2 vector.range(d$hours)
tapplybaseApply a function to a vector, grouped by a factor.tapply(d$hours, d$grp, mean)
pfbaseCumulative distribution function of the FF distribution.pf(4.2, df1 = 1, df2 = 23, lower.tail = FALSE)

Chapter 10: Remedial measures and transformations

FunctionPackagePurposeExample
logbaseNatural logarithm (base ee).log(d$body)
boxcoxMASSProfile log-likelihood plot for the Box-Cox family of power transformations.MASS::boxcox(fit)
qchisqbaseQuantile (inverse CDF) of the chi-squared distribution.qchisq(0.95, df = 1)
rlmMASSFit a robust regression by iteratively reweighted least squares, down-weighting outliers.MASS::rlm(y ~ x, data = d)
rbindbaseBind vectors or data frames together as rows.rbind(row1, row2)

Chapter 11: Categorical predictors and interactions

FunctionPackagePurposeExample
relevelbaseChange which level of a factor is the reference (baseline) level.d$rank <- relevel(d$rank, ref = "AsstProf")
model.matrixbaseBuild the design matrix X\mathbf{X} a model uses, including dummy columns.model.matrix(fit)
IbaseProtect an expression from formula notation, so it is used as-is.lm(y ~ x + I(x^2), data = d)
pmaxbaseElementwise maximum across two or more vectors.pmax(0, x - 5)
expand.gridbaseBuild a data frame of every combination of the given values.expand.grid(x = 1:3, grp = c("a", "b"))
tablebaseCross-tabulate one or more factors.table(d$rank, d$sex)

Chapter 12: Multicollinearity, variable selection, and validation

FunctionPackagePurposeExample
vifcarVariance inflation factors, a multicollinearity diagnostic.car::vif(fit)
regsubsetsleapsBest-subsets search across candidate predictors.leaps::regsubsets(y ~ ., data = d)
AICbaseAkaike information criterion of a fitted model.AIC(fit)
BICbaseBayesian (Schwarz) information criterion of a fitted model.BIC(fit)
orderbaseIndices that would sort a vector.order(d$hours)
formulabaseExtract or build a model formula object.formula(fit)
glmnetglmnetFit a ridge, lasso, or elastic-net penalized regression path.glmnet::glmnet(as.matrix(X), y, alpha = 1)
cv.glmnetglmnetCross-validated glmnet fit, chooses the penalty by held-out error.glmnet::cv.glmnet(as.matrix(X), y, alpha = 1)
as.matrixbaseCoerce a data frame to a plain numeric matrix.as.matrix(d[, c("x1", "x2")])

Chapter 13: Logistic regression

FunctionPackagePurposeExample
glmbaseFit a generalized linear model (here, with family = binomial).glm(damage_bin ~ temp, data = d, family = binomial)
confint.defaultbaseWald (asymptotic Normal) confidence intervals for a glm’s coefficients.confint.default(fit)
drop1baseCompare a model to each of its one-term-simpler versions (likelihood-ratio tests).drop1(fit, test = "Chisq")
expbaseExponential function; converts a log-odds coefficient to an odds ratio.exp(coef(fit))
pchisqbaseCumulative distribution function of the chi-squared distribution.pchisq(5.2, df = 1, lower.tail = FALSE)
outerbaseOuter product: apply a function to every pair from two vectors.outer(1:3, 1:3, "+")
cutbaseCut a numeric vector into labeled bins (used to build calibration groups).cut(fitted(fit), breaks = 5)

Chapter 14: Poisson regression and the GLM idea

FunctionPackagePurposeExample
poissonbaseFamily object for Poisson glm fits (log link by default).glm(count ~ x, data = d, family = poisson)
quasipoissonbaseFamily object for overdispersed count data; same mean model, inflated variance.glm(count ~ x, data = d, family = quasipoisson)
gaussianbaseFamily object for glm fits with a Normal response (recovers ordinary lm).glm(y ~ x, data = d, family = gaussian)
df.residualbaseResidual degrees of freedom of a fitted model.df.residual(fit)
glm.nbMASSNegative-binomial regression, for overdispersed counts.MASS::glm.nb(count ~ x, data = d)

Chapter 15: Regression with time: autocorrelation and forecasting

FunctionPackagePurposeExample
seq_lenbaseGenerate the sequence 1, 2, ..., n.seq_len(nrow(d))
diffbaseLagged differences of a vector.diff(d$passengers)
subsetbaseFilter rows of a data frame by a logical condition.subset(d, year >= 1955)

Chapter 16: Path analysis and a look ahead

No new functions beyond those already tabulated in earlier chapters; Chapter 16 reuses lm, coef, cor, scale, cooks.distance, factor, and relevel to build a path model from a sequence of ordinary regressions.

See Appendix D: Python Reference for the equivalent lookup table in Python, and Appendix E: The Datasets of This Book for full documentation of every dataset named in the examples above.