1Objectives¶
By the end of this lesson you will be able to:
Explain what an R package is and why this course standardizes on two.
Load
mosaicandBSDAat the start of a session withlibrary().Read and use the
mosaicformula interface,goal( y ~ x, data = ), for a summary function.Explain what
BSDAadds that base R does not have.
2What a package is¶
Base R (what you get straight from installing R) already does a lot, but most of the specialized tools statisticians actually use live in packages — bundles of extra functions, written and reviewed by the R community, that you add on top of base R. You met the install step already in L02:
install.packages(c("mosaic", "BSDA")) # once per computerInstalling a package downloads it onto your computer, permanently — like
installing an app. It does not make its functions available yet. For
that, every new R session needs one more step: library().
library(mosaic)
library(BSDA)Run those two lines at the top of every script or notebook in this
course, before any mosaic/BSDA function. library() is cheap to run and
you cannot “over-load” a package, so when in doubt, run it again.
3What actually happens when you library(mosaic)¶
The first time you load mosaic in a session, it prints a block of
messages — real output, not an error:
library(mosaic)Registered S3 method overwritten by 'mosaic':
method from
fortify.SpatialPolygonsDataFrame ggplot2
The 'mosaic' package masks several functions from core packages in order to add
additional features. The original behavior of these functions should not be affected by this.
Attaching package: 'mosaic'
The following objects are masked from 'package:dplyr':
count, do, tally
The following object is masked from 'package:Matrix':
mean
The following object is masked from 'package:ggplot2':
stat
The following objects are masked from 'package:stats':
binom.test, cor, cor.test, cov, fivenum, IQR, median, prop.test,
quantile, sd, t.test, var
The following objects are masked from 'package:base':
max, mean, min, prod, range, sample, sum“Masks” means mosaic replaces a handful of base R functions — mean,
sd, cor, t.test, prop.test, and others — with versions that also
understand the ~ formula. This is deliberate and is why the course uses
mosaic: it means the exact same function name (mean(), t.test()) works
both the old way, on a bare vector, and the new way, on a whole data frame
with data = . Nothing breaks; you simply gain an option. Every lesson from
here on suppresses these startup messages with suppressMessages() so the
book’s code blocks show only the output that matters:
suppressMessages({
library(mosaic)
library(BSDA)
})You do not need suppressMessages() yourself — seeing the real messages
once, above, is enough to recognize them as normal.
4The formula interface, one more time, with real code¶
The one idea that unlocks mosaic is its formula interface (also
summarized in the R quick reference): read
y ~ x as “y broken down by x.” A bare ~x (nothing on
the left) means “just x, as one group.” Watch the same function,
favstats(), answer two different questions just by changing the formula:
survey <- read.csv("data/survey_sim.csv")
favstats(~ sleep_hours, data = survey) min Q1 median Q3 max mean sd n missing
3.9 6.1 6.8 7.425 9.1 6.7875 1.012241 120 0That’s every student’s sleep hours summarized as one group. Now put
pet on the right of ~:
favstats(sleep_hours ~ pet, data = survey) pet min Q1 median Q3 max mean sd n missing
1 Cat person 4.2 6.075 6.65 7.20 9.1 6.687500 1.0268667 40 0
2 Dog person 3.9 6.050 6.80 7.55 8.8 6.763636 1.0660352 55 0
3 Neither 5.3 6.600 7.00 7.50 8.6 7.000000 0.8631338 25 0Same function, same data = argument — only the formula changed, and now
you get sleep-hours statistics broken down by pet preference: one row per
group (40 cat people, 55 dog people, 25 neither), each with its own mean,
SD, and so on. L07 uses favstats() and tally() this way
constantly; the pattern is worth having cold before then.
A quick check that mosaic’s formula-aware mean() and base R’s plain
mean() agree, since mosaic is only adding an option, not replacing the
answer:
mean(~ sleep_hours, data = survey) # mosaic's formula version
mean(survey$sleep_hours) # base R's version, from L04[1] 6.7875
[1] 6.7875Identical, as they must be — same 120 numbers, same arithmetic, two ways of telling R which numbers to average.
5tally(): mosaic’s table function¶
tally() is mosaic’s formula-driven counter for categorical variables —
L07 and L11 (chi-square) both lean on it heavily.
A one-variable tally:
tally(~ pet, data = survey)pet
Cat person Dog person Neither
40 55 25 That’s a frequency count of the pet column — read it as “40 students are
cat people, 55 are dog people, 25 are neither,” which sums to the 120 rows
you saw with nrow(survey) in L04. tally(y ~ x, data = ) for
a two-way table, and proportions instead of counts, are both covered in full
in L07.
6What BSDA adds: summary-statistics tests¶
Every test you’ll meet from L09 onward has two “shapes” a textbook problem can hand you:
Raw data — a column of actual observations.
mosaic’s maskedt.test()/prop.test()(andmean,sd, etc.) handle this shape.Summary statistics only — you’re told , , , with no raw data at all. Base R and
mosaichave no function for this shape —BSDAis the fix.
BSDA supplies zsum.test() (z-test from summary stats, known)
and tsum.test() (t-test from summary stats). Here is a one-sample z-test
of hours of sleep, using only the summary numbers from the
favstats() output above — no raw data needed:
zsum.test(mean.x = 6.7875, sigma.x = 1.1, n.x = 120,
mu = 7, alternative = "two.sided")
One-sample z-Test
data: Summarized x
z = -2.1162, p-value = 0.03433
alternative hypothesis: true mean is not equal to 7
95 percent confidence interval:
6.590689 6.984311
sample estimates:
mean of x
6.7875
You are not expected to read every line of that output yet — L10
teaches hypothesis-test output in full. Notice only the shape of the
input: four named arguments (mean.x, sigma.x, n.x, mu), no data
frame, no raw column — exactly what a “you are told , , and
” problem gives you. z.test() (no sum) is BSDA’s raw-data sibling,
used when you do have the actual observations and a known :
set.seed(2200)
sample_vals <- rnorm(25, mean = 6.7, sd = 1.1)
z.test(sample_vals, mu = 7, sigma.x = 1.1)
One-sample z-Test
data: sample_vals
z = -0.8482, p-value = 0.3963
alternative hypothesis: true mean is not equal to 7
95 percent confidence interval:
6.382203 7.244587
sample estimates:
mean of x
6.813395
Same test, same package, but this time z.test() takes a vector of 25
actual values (sample_vals) instead of three summary numbers. tsum.test()
and t.test() follow the identical raw-vs-summary pattern for the
-distribution case, starting in L10.
7mosaic vs. BSDA: which one for which task¶
| You have... | You want... | Use |
|---|---|---|
| A data frame column | A numerical summary | favstats(~x, data=) (mosaic) |
| A data frame column | A frequency table | tally(~x, data=) (mosaic) |
| A data frame + a formula | A plot | gf_histogram, gf_boxplot, ... (mosaic/ggformula) |
| A data frame column | A t-test or proportion test | t.test(~x, data=), prop.test(...) (mosaic) |
| Only , , (no raw data) | A t-test | tsum.test(...) (BSDA) |
| Only , , (no raw data) | A z-test | zsum.test(...) (BSDA) |
| A vector + known | A z-test | z.test(...) (BSDA) |
This table narrows the course’s two-package toolkit down to “which package for which task.” Keep coming back to it — nearly every function this book teaches is one of these two packages.
8Summary¶
A package adds functions on top of base R;
install.packages()gets it onto your computer (once),library()makes it usable (every session).This course uses exactly
mosaic(+ggformula) andBSDAfor every statistical task — see the table above for which one to reach for.mosaic’s formula interface,goal( y ~ x, data = ), is one grammar for summaries (favstats), tables (tally), plots (gf_*), and inference — ready ~ xas “y broken down by x,” and~xalone as “just x.”BSDAadds the tests base R lacks:zsum.test/tsum.testfrom summary statistics only, andz.testfor raw data with known .