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.

1Objectives

By the end of this lesson you will be able to:

  1. Explain what an R package is and why this course standardizes on two.

  2. Load mosaic and BSDA at the start of a session with library().

  3. Read and use the mosaic formula interface, goal( y ~ x, data = ), for a summary function.

  4. Explain what BSDA adds 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 computer

Installing 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       0

That’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       0

Same 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.7875

Identical, 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:

  1. Raw data — a column of actual observations. mosaic’s masked t.test()/prop.test() (and mean, sd, etc.) handle this shape.

  2. Summary statistics only — you’re told xˉ=6.7875\bar{x}=6.7875, s=1.1s=1.1, n=120n=120, with no raw data at all. Base R and mosaic have no function for this shape — BSDA is the fix.

BSDA supplies zsum.test() (z-test from summary stats, σ\sigma known) and tsum.test() (t-test from summary stats). Here is a one-sample z-test of H0:μ=7H_0: \mu = 7 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 xˉ\bar{x}, σ\sigma, and nn” problem gives you. z.test() (no sum) is BSDA’s raw-data sibling, used when you do have the actual observations and a known σ\sigma:

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 tt-distribution case, starting in L10.

7mosaic vs. BSDA: which one for which task

You have...You want...Use
A data frame columnA numerical summaryfavstats(~x, data=) (mosaic)
A data frame columnA frequency tabletally(~x, data=) (mosaic)
A data frame + a formulaA plotgf_histogram, gf_boxplot, ... (mosaic/ggformula)
A data frame columnA t-test or proportion testt.test(~x, data=), prop.test(...) (mosaic)
Only xˉ\bar{x}, ss, nn (no raw data)A t-testtsum.test(...) (BSDA)
Only xˉ\bar{x}, σ\sigma, nn (no raw data)A z-testzsum.test(...) (BSDA)
A vector + known σ\sigmaA z-testz.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