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.

A one-page cheat sheet for the R you use all semester: loading data, the one formula pattern that runs through every command, and the mosaic + BSDA functions that carry the course’s statistics — each with a runnable one-line example. Every function here matches what the Shiny Statistics Explorer shows you and what the which-test guide recommends, so the syntax is the same everywhere you meet it.


11. Getting started in every session

library(mosaic)   # summaries, plots (ggformula), simulation, inference
library(BSDA)     # z/t tests from summary statistics (zsum.test, tsum.test)

Loading mosaic also loads ggformula (the gf_* plots) and dplyr (the wrangling verbs in §4), so this pair of lines is all you need. On CSUB JupyterHub these packages are pre-installed — you install nothing.


22. Importing data

The curated course datasets live in data/processed/. Read one into a data frame with read.csv(), then pass that data frame to data = everywhere else.

TaskCodeNotes
Load a course datasetair <- read.csv("data/processed/kern_airquality.csv")assign it a short name; use that name in data =
Read your own CSV filedat <- read.csv("myfile.csv")a relative path is looked up from your working folder
Peek at structureglimpse(air)variable names, types, first values
Quick summary of every columninspect(air)mosaic: numeric and categorical summaries at once
First / last rowshead(air) · tail(air)default 6 rows
Dimensionsdim(air) · nrow(air) · ncol(air)rows × columns
Column namesnames(air)

See the dataset index for what each curated file contains.


33. The formula interface at a glance

One pattern, three jobs. Wherever you see goal(formula, data = D), the same two formula shapes apply:

You want…Formula shapeExample
one variable~ yfavstats(~ daily_mean, data = air)
a variable by a groupy ~ xfavstats(daily_mean ~ site_name, data = air)
one categorical variable~ ytally(~ category, data = crops)
a two-way table~ y + xtally(~ category + is_synthetic, data = crops)
an association (two numeric)y ~ xgf_point(yield_per_acre ~ harvested_acres, data = crops)

The ~ is read “by.” You will use these five shapes for the rest of the course.


44. Preparing data (a few dplyr verbs)

mosaic loads dplyr, whose verbs read like sentences. The pipe |> (“then”) passes one step’s result into the next. You need only a handful:

VerbWhat it doesOne-line example
filter()keep rows that match a conditionfilter(air, pollutant == "PM2.5")
select()keep (or drop) columnsselect(air, date, site_name, daily_mean)
mutate()add or change a columnmutate(air, over = daily_mean > 35)
arrange()sort rowsarrange(air, desc(daily_mean))

Piping them together (keep PM2.5 rows, then summarise by site):

air |>
  filter(pollutant == "PM2.5") |>
  favstats(daily_mean ~ site_name, data = _)

The == tests equality (“is the pollutant exactly PM2.5?”); desc() sorts largest-first.


55. Describe & visualize

GoalCodeProduces
Numerical summary of a variablefavstats(~ daily_mean, data = air)min, Q1, median, Q3, max, mean, sd, n, missing
Same summary, by groupfavstats(daily_mean ~ site_name, data = air)one row of summaries per group
A single statisticmean(~ daily_mean, data = air) · sd(...) · median(...) · IQR(...)one number (formula form)
Frequency table (categorical)tally(~ category, data = crops)counts per category
Proportions instead of countstally(~ category, data = crops, format = "proportion")shares per category
Two-way tabletally(~ category + is_synthetic, data = crops)cross-tabulation
Histogramgf_histogram(~ daily_mean, data = air)distribution of one numeric variable
Boxplot (optionally by group)gf_boxplot(daily_mean ~ site_name, data = air)center/spread/outliers across groups
Bar chart (categorical)gf_bar(~ category, data = crops)counts per category
Scatterplotgf_point(yield_per_acre ~ harvested_acres, data = crops)relationship between two numerics
Scatterplot + fitted linegf_point(yield_per_acre ~ harvested_acres, data = crops) %>% gf_lm()least-squares line over the points

The gf_* helpers (from ggformula) return ggplot objects, so you can add labels and a colorblind-safe palette. Define the Okabe–Ito colors once and apply them with gf_refine():

okabe_ito <- c("#0072B2","#E69F00","#009E73","#CC79A7",
               "#56B4E9","#D55E00","#F0E442","#999999")
gf_boxplot(daily_mean ~ site_name, fill = ~ site_name, data = air) %>%
  gf_refine(scale_fill_manual(values = okabe_ito))

66. Probability, the Normal model & simulation

GoalCodeNotes
Normal area, with picturexpnorm(42, mean = 30, sd = 8)prints the z-score and both tail probabilities and shades the curve; add lower.tail = FALSE for the upper tail
Normal percentile (cutoff)xqnorm(0.95, mean = 30, sd = 8)the value with 95% below it
Draw a Normal curveplotDist("norm", mean = 30, sd = 8)the model on its own
Binomial probabilitydbinom(3, size = 10, prob = 0.4)exactly 3 successes; pbinom() for “≤ 3”, xpbinom() draws it
Build a sampling distributiondo(1000) * mean(~ daily_mean, data = resample(air))resample-and-recompute; the CLT in action
Flip / draw at randomrflip(10) · resample(x) · shuffle(x) · sample(x)the building blocks of a simulation

xpnorm() is the teaching tool: it shows its work — the z-score, the tail areas, and the shaded curve — so you can read why, not just the number. Set a seed (set.seed(2200)) before any do() simulation so your result is reproducible.


77. Inference: tests, intervals, models

Pick the right procedure with the which-test guide. Every test below prints a decision and a confidence interval; pull the interval alone with confint(model) or result$conf.int.

ProcedureCodeUsed in
One proportion (CI + test)prop.test(x = 12, n = 40, p = 0.5)Ch. 9
Two proportionsprop.test(c(30, 45), c(100, 120))Ch. 9
One mean, raw data (t)t.test(~ daily_mean, data = air, mu = 35)Ch. 10
One mean from summary stats (t)tsum.test(mean.x = 36.2, s.x = 8.1, n.x = 40, mu = 35)Ch. 10
One mean from summary stats (z, σ known)zsum.test(mean.x = 36.2, sigma.x = 8, n.x = 40, mu = 35)Ch. 10
One mean, raw data (z, σ known)z.test(x, mu = 35, sigma.x = 8)Ch. 10
Two means, independent (Welch t)t.test(active_minutes ~ group, data = fit)Ch. 10
Paired meanst.test(after, before, paired = TRUE)Ch. 10
Chi-square goodness of fitchisq.test(tally(~ category, data = crops), p = rep(1/5, 5))Ch. 11
Chi-square independence (shows expected)xchisq.test(tally(~ sex + bmi_who, data = nhanes))Ch. 11
One-way ANOVA (F)anova(aov(daily_mean ~ site_name, data = air))Ch. 12
Correlationcor(yield_per_acre ~ harvested_acres, data = crops)Ch. 13
Linear regression (coefficient table)msummary(lm(yield_per_acre ~ harvested_acres, data = crops))Ch. 13

xchisq.test() prints the observed and expected counts with residuals — exactly the table Ch. 11 teaches you to read. msummary() prints the coefficient table (estimate, SE, t, p) plus R2R^2.


88. Reading the table & distribution functions directly

When you need a raw probability or critical value (and want to check software against the distribution tables):

DistributionArea from a valueValue from an area
Normalpnorm(z)qnorm(p)
t (with df)pt(t, df)qt(p, df)
Chi-squarepchisq(x, df, lower.tail = FALSE)qchisq(1 - a, df)
Fpf(F, df1, df2, lower.tail = FALSE)qf(1 - a, df1, df2)
Binomialpbinom(k, size = n, prob = p)qbinom(p, size = n, prob = p)

99. Reproducibility habits

HabitCodeWhy
Fix randomnessset.seed(2200)same simulation result every run
Comment your steps# what this line doesfuture-you and your grader thank you
Keep raw data read-onlyload, then mutate() into a new objectnever overwrite the original
Report your R versionsessionInfo()makes results reproducible by others