MATH U113 · Probability & Statistics · R lab support
The Lab Assignment, from zero
All three questions, worked from zero: what each part is really asking, the base-R code, the output it actually prints (every line here was run in R 4.6.2), and what to write as the answer. It finishes with how to turn it all into the typed PDF the instructions ask for. Due Wednesday 4 November 2026, on Google Classroom.
What it's built from: the three lab sheets you already have. Q1 is Lab 1 (descriptive statistics) applied to a new dataset. Q2 is Lab 2 (rbinom, rexp, dpois). Q3 is Lab 3 with two new populations. Nothing on it is beyond the three sheets plus the CLT, and the CLT has its own page: R lab 3, from zero. Read that first if you haven't, because Q3 is half the marks.
Marks: Q1 = 5, Q2 = 5, Q3 = 10. Time: about 4–5 hours in total. Day 1 (today or Monday): the Lab 3 page, then Q1. Day 2 (Tuesday): Q2 and Q3. Assemble and submit Tuesday night, a day early. The sheet gives a date but no time, and Classroom uploads fail at the worst moments.
How to use this page: it's graded work, so the report has to be yours. Type the code yourself (don't paste it), run it, and check that your output matches the output shown here. Then write the answers in your own words, using the "what to write" notes as a checklist of points to cover. Typing is also how the code ends up in your head for the lab exam.
0 · Set up once
- Open RStudio and create a script: File → New File → R Script. Save it straight away as
lab-assignment.R. A script is a file you can re-run. The console is a scratchpad. - Run a line with ⌘ + Return (Ctrl + Enter on Windows). It runs the line the cursor is on, or everything you've highlighted. Output appears in the Console. Plots appear in the Plots pane.
- Base R only. No packages to install.
irisis built into R, sodata(iris)just loads it. set.seed(123)appears before each simulation. It makes the "random" numbers repeat exactly, so your output will match the numbers on this page digit for digit. If something differs, you've typed something differently. That's a free error check.
Question 1 · The iris data 5 marks · Lab 1 · Devore ch. 1
iris is 150 flowers, 50 from each of three species (setosa, versicolor, virginica), with four measurements in cm. You need two columns: Sepal.Length and Petal.Length. The $ sign pulls one column out of a table, and short names save typing:
# ================= Question 1: iris =================
data(iris)
sl <- iris$Sepal.Length
pl <- iris$Petal.Length
get_modes <- function(x) { # base R has no mode function
counts <- table(x)
as.numeric(names(counts)[counts == max(counts)])
}
get_modes is Lab 1's function. R has no built-in function for the mode (mode() exists, but it tells you the data type, which is a trap in itself). table(x) counts how often each value occurs, and the function returns every value whose count equals the maximum. That matters here, because one variable has two modes.
1.1 · Centre, spread, and which variable separates the species
# 1.1 measures of centre and spread
stats <- data.frame(
variable = c("Sepal.Length", "Petal.Length"),
mean = c(mean(sl), mean(pl)),
median = c(median(sl), median(pl)),
mode = c(paste(get_modes(sl), collapse = ", "),
paste(get_modes(pl), collapse = ", ")),
variance = c(var(sl), var(pl)),
sd = c(sd(sl), sd(pl))
)
print(stats, digits = 4)
# species-wise means and SDs
print(aggregate(cbind(Sepal.Length, Petal.Length) ~ Species, data = iris, FUN = mean))
print(aggregate(cbind(Sepal.Length, Petal.Length) ~ Species, data = iris, FUN = sd))
Output
variable mean median mode variance sd
1 Sepal.Length 5.843 5.80 5 0.6857 0.8281
2 Petal.Length 3.758 4.35 1.4, 1.5 3.1163 1.7653
Species Sepal.Length Petal.Length
1 setosa 5.006 1.462
2 versicolor 5.936 4.260
3 virginica 6.588 5.552
Species Sepal.Length Petal.Length
1 setosa 0.3524897 0.1736640
2 versicolor 0.5161711 0.4699110
3 virginica 0.6358796 0.5518947
aggregate(… ~ Species, FUN = mean) reads "the mean of these columns, split by species". The second aggregate gives the within-species SDs. You need those to make the "distinguishes" argument properly.
What to writeWhich variable better distinguishes the species?
- Report the table: Sepal.Length has mean 5.843, median 5.80, mode 5.0, variance 0.6857, SD 0.8281. Petal.Length has mean 3.758, median 4.35, two modes (1.4 and 1.5, each occurring 13 times), variance 3.1163, SD 1.7653.
- Species means. Petal: 1.462, 4.260, 5.552. Sepal: 5.006, 5.936, 6.588.
- The argument: compare the gaps between species with the spread within a species. For petal length, setosa and versicolor are 2.8 cm apart, while each species' SD is under 0.6 cm, so the groups barely touch (setosa petals run 1.0–1.9 cm and versicolor's 3.0–5.1 cm, with no overlap at all). For sepal length, neighbouring species are only 0.65–0.93 cm apart, with SDs of 0.35–0.64 cm, so the species overlap heavily.
- Conclusion: Petal.Length distinguishes the species better. Its species means are far apart compared with the variation inside each species.
"Petal length's means are more different (1.46 to 5.55 against 5.01 to 6.59), so it distinguishes better." That's half an argument. Means 4 cm apart would be useless if each species varied by ±5 cm. The comparison is gap between means against spread within a group. That's why the second aggregate line is there. (It's also the idea behind the hypothesis tests in Module 6.)
1.2 · Five-number summaries and percentiles
# 1.2 five-number summaries and percentiles
print(fivenum(sl))
print(fivenum(pl))
print(quantile(sl, probs = c(0.12, 0.60, 0.90)))
Output
[1] 4.3 5.1 5.8 6.4 7.9 [1] 1.00 1.60 4.35 5.10 6.90 12% 60% 90% 4.9 6.1 6.9
The five-number summary is minimum, lower quartile, median, upper quartile, maximum, the five numbers a boxplot is drawn from. So: Sepal.Length: 4.3, 5.1, 5.8, 6.4, 7.9. Petal.Length: 1.0, 1.6, 4.35, 5.1, 6.9.
The p-th percentile is the value with p% of the data at or below it. quantile(sl, probs = c(0.12, 0.60, 0.90)) gives the 12th, 60th and 90th percentiles of sepal length: 4.9, 6.1 and 6.9 cm. So about 12% of flowers have sepals of 4.9 cm or less, and 10% have sepals longer than 6.9 cm.
Unpack: "but quantile() has nine types"
R offers nine slightly different percentile rules (type = 1 to 9), and Devore uses yet another. They can disagree when a percentile falls between two data values. We checked all nine for these three percentiles and every one gives 4.9, 6.1, 6.9, because iris has many repeated values. summary(sl) also prints the same quartiles, plus the mean.
1.3 · IQR and outliers
The interquartile range is upper quartile minus lower quartile, the width of the middle half of the data. The 1.5 × IQR rule calls a value a potential outlier if it lies more than 1.5 IQRs beyond either quartile. That gives two "fences":
# 1.3 IQR and the 1.5 x IQR rule
iqr_sl <- IQR(sl)
q_sl <- quantile(sl, c(0.25, 0.75))
lower <- q_sl[1] - 1.5 * iqr_sl
upper <- q_sl[2] + 1.5 * iqr_sl
cat("IQR of Sepal.Length:", iqr_sl, "\n")
cat("Fences:", lower, "to", upper, "\n")
cat("Outliers:", sl[sl < lower | sl > upper], "\n") # prints nothing if none
cat("IQR of Petal.Length:", IQR(pl), "\n")
Output
IQR of Sepal.Length: 1.3 Fences: 3.15 to 8.35 Outliers: IQR of Petal.Length: 3.5
What to writeStep by step
- IQR = 6.4 − 5.1 = 1.3 cm.
- Fences: 5.1 − 1.5 × 1.3 = 5.1 − 1.95 = 3.15 and 6.4 + 1.95 = 8.35.
- Outliers: the data run from 4.3 to 7.9, entirely inside [3.15, 8.35], so Sepal.Length has no potential outliers. "Outliers:" printing nothing is R's way of saying none. The boxplot in 1.4 agrees: no dots beyond the whiskers.
- Larger IQR: Petal.Length, 5.1 − 1.6 = 3.5 cm against 1.3 cm. Its middle half is spread across almost three times the range, because it straddles the gap between setosa (short petals) and the other two species.
1.4 · Histograms and boxplots
# 1.4 histograms and boxplots
par(mfrow = c(2, 2))
hist(sl, col = "steelblue", border = "white",
main = "Histogram of Sepal Length", xlab = "Sepal length (cm)", ylab = "Frequency")
hist(pl, col = "darkcyan", border = "white",
main = "Histogram of Petal Length", xlab = "Petal length (cm)", ylab = "Frequency")
boxplot(sl, horizontal = TRUE, col = "steelblue",
main = "Boxplot of Sepal Length", xlab = "Sepal length (cm)")
boxplot(pl, horizontal = TRUE, col = "darkcyan",
main = "Boxplot of Petal Length", xlab = "Petal length (cm)")
par(mfrow = c(1, 1))
par(mfrow = c(2, 2)) puts the four plots on one 2 × 2 figure, which makes the report shorter. The last line resets it. Each plot gets main (title), xlab and ylab, because the question asks for "appropriate titles and axis labels" and that's an easy mark to drop. Here's what R draws, recomputed from the same 150 values:
What to writeWhich histogram is more asymmetric?
- Petal.Length. Its histogram is two separate clumps: a tall, narrow one at 1–2 cm (all 50 setosa) and a broad one from 3 to 7 cm (the other 100 flowers), with an empty bin in between. Nothing on the left mirrors the right.
- The numbers agree: its mean (3.76) sits well below its median (4.35), pulled left by the setosa clump. In the boxplot the median line sits far to the right of the box's centre (4.35 inside a box from 1.6 to 5.1).
- Sepal.Length, by contrast, is a single hump with a slightly longer right tail. Its mean (5.84) and median (5.80) nearly coincide, and the median sits near the middle of its box.
Lab 1's skewness coefficient gives +0.31 for sepal and −0.27 for petal, so by that one number sepal looks slightly more skewed. That's misleading. The coefficient is built for single-hump shapes, and for a two-clump histogram the clumps' contributions partly cancel. The question says "appears", so judge by the picture, and back the judgement with the mean–median gap: 0.59 cm for petal against 0.04 cm for sepal. If you do mention the coefficient, say why you aren't relying on it. That earns credit rather than costing it.
Question 2 · Two simulation experiments 5 marks · Lab 2 · §3.4, §3.6, §4.4
2.1 · Binomial(n, 5/n) against Poisson(5)
The idea first. Binomial(n, p) counts successes in n trials. If the trials are many and success is rare, the count behaves like a Poisson with λ = np (§3.6). Here p = 5/n, so the expected count is always np = 5. Only the "many trials, rare success" part changes as n goes 20 → 100 → 500 (p = 0.25 → 0.05 → 0.01).
# ================= Question 2.1: Binomial(n, 5/n) vs Poisson(5) =================
set.seed(123)
N <- 10000
n_vals <- c(20, 100, 500)
k <- 0:15
par(mfrow = c(1, 3))
for (n in n_vals) {
x <- rbinom(N, size = n, prob = 5 / n)
sim_p <- sapply(k, function(j) mean(x == j)) # simulated P(X = j)
plot(k - 0.15, sim_p, type = "h", lwd = 4, col = "steelblue",
ylim = c(0, 0.22), xlab = "k", ylab = "Probability",
main = paste0("Binomial(", n, ", 5/", n, ") vs Poisson(5)"))
points(k + 0.15, dpois(k, 5), type = "h", lwd = 4, col = "red")
legend("topright", c("simulated binomial", "Poisson(5)"),
col = c("steelblue", "red"), lwd = 4, bty = "n")
cat("n =", n, " sample mean =", mean(x), " sample var =", round(var(x), 4),
" max|sim - Poisson| =", round(max(abs(sim_p - dpois(k, 5))), 4),
" max|exact binom - Poisson| =", round(max(abs(dbinom(k, n, 5/n) - dpois(k, 5))), 4), "\n")
}
par(mfrow = c(1, 1))
Two new pieces. mean(x == j) is the fraction of the 10,000 draws equal to j, the simulated P(X = j). x == j is a TRUE/FALSE vector, and R counts TRUE as 1, so its mean is a proportion. sapply repeats that for j = 0, 1, …, 15. type = "h" draws vertical bars, and the ±0.15 shifts put the blue and red bars side by side instead of on top of each other.
Output
n = 20 sample mean = 4.9845 sample var = 3.6698 max|sim - Poisson| = 0.0315 max|exact binom - Poisson| = 0.0269 n = 100 sample mean = 4.974 sample var = 4.6958 max|sim - Poisson| = 0.0077 max|exact binom - Poisson| = 0.0046 n = 500 sample mean = 4.9994 sample var = 4.9671 max|sim - Poisson| = 0.0069 max|exact binom - Poisson| = 9e-04
dpois(k, 5). At n = 20 the binomial is visibly taller in the middle and thinner in the tails.What to writeFor which n is the approximation most accurate, and why?
- n = 500. At n = 20 the binomial is visibly too concentrated: too tall at 4–6, too short in the tails. At 100 and 500 the bars nearly coincide.
- Why, from the variances. Both distributions have mean 5. The Poisson's variance is also 5, but the binomial's is np(1 − p) = 5(1 − 5/n): 3.75, 4.75, 4.95 for n = 20, 100, 500. The simulated variances (3.67, 4.70, 4.97) show the same thing. The factor (1 − p) is the only difference, and it approaches 1 as p = 5/n shrinks. That's the "n large, p small" condition at work.
- The exact gap, using
dbinomagainstdpoiswith no simulation: the largest difference in any single probability is 0.0269, 0.0046, 0.0009. Each fivefold increase in n cuts it roughly fivefold. For example, P(X = 0) is 0.0032, 0.0059, 0.0066 against the Poisson's 0.0067.
Look at the simulated column: the largest gap is 0.0077 at n = 100 and 0.0069 at n = 500, hardly different. That's not because 500 is no better. With 10,000 draws, a simulated probability near 0.175 wobbles by about √(0.175 × 0.825/10000) ≈ 0.004 on its own, which swamps the true gap of 0.0009. Simulation can't see differences smaller than its own noise. That's why the exact dbinom comparison is in the code, and quoting it makes your "most accurate" answer airtight.
2.2 · Exponential lifetimes: estimating P(X > 6)
Theory first. Mean 4 years means rate λ = 1/4 per year. Remember Lab 2's trap: R's rexp wants the rate. The exponential tail is P(X > x) = e−λx, so
The simulation estimates it the obvious way: generate n lifetimes and count what fraction exceed 6. mean(life > 6) is the same TRUE-counts-as-1 trick as in 2.1.
# ================= Question 2.2: exponential lifetimes, mean 4 years =================
p_true <- 1 - pexp(6, rate = 1/4) # = exp(-1.5)
cat("Theoretical P(X > 6) =", p_true, "\n")
set.seed(123)
for (n in c(100, 1000, 10000)) {
life <- rexp(n, rate = 1/4)
est <- mean(life > 6)
cat("n =", n, " estimate =", est, " abs error =", round(abs(est - p_true), 4), "\n")
}
# typical error: repeat each experiment 1000 times
set.seed(123)
for (n in c(100, 1000, 10000)) {
ests <- replicate(1000, mean(rexp(n, rate = 1/4) > 6))
cat("n =", n, " SD of 1000 estimates =", round(sd(ests), 4),
" theory sqrt(p(1-p)/n) =", round(sqrt(p_true * (1 - p_true) / n), 4), "\n")
}
Output
Theoretical P(X > 6) = 0.2231302 n = 100 estimate = 0.23 abs error = 0.0069 n = 1000 estimate = 0.229 abs error = 0.0059 n = 10000 estimate = 0.2238 abs error = 7e-04 n = 100 SD of 1000 estimates = 0.0414 theory sqrt(p(1-p)/n) = 0.0416 n = 1000 SD of 1000 estimates = 0.0129 theory sqrt(p(1-p)/n) = 0.0132 n = 10000 SD of 1000 estimates = 0.0042 theory sqrt(p(1-p)/n) = 0.0042
What to writeHow does the accuracy change as n increases?
- The estimates: 0.2300, 0.2290, 0.2238 against the true 0.2231. The errors are 0.0069, 0.0059 and 0.0007.
- Be honest about one run: the n = 100 run happened to be lucky. Its error is barely bigger than at 1000. A single run can't show the trend reliably, which is why the code's last loop repeats each experiment 1000 times (
replicate) and measures the typical error, the SD of the 1000 estimates: 0.0414, 0.0129, 0.0042. - The pattern: each tenfold increase in n shrinks the typical error by about √10 ≈ 3.2 times (0.041 → 0.013 → 0.004). It matches the formula √(p(1 − p)/n) almost exactly. The accuracy improves, but slowly: 100 times more simulations buys only 10 times more accuracy.
Unpack: where √(p(1 − p)/n) comes from
Each lifetime contributes a 1 (it exceeds 6) or a 0, which is a Bernoulli variable with variance p(1 − p). The estimate is the mean of n of these, so by Lab 3's rule its SD is σ/√n = √(p(1 − p))/√n. With p = 0.2231 and n = 100, that's 0.4163/10 = 0.0416.
Question 3 · Sampling distributions and the CLT 10 marks · Lab 3 · §5.3–5.4
This is Lab 3 with the exponential swapped for two new populations, and with bigger n and B. Start by writing down each population's mean and SD. Everything else follows from them.
| Population | Mean μ | Variance σ2 | SD σ | Where from |
|---|---|---|---|---|
| X ~ Uniform(0, 1) | 0.5 | 1/12 = 0.0833 | 0.2887 | (a + b)/2 and (b − a)2/12 §4.1–4.2 |
| Y ~ Binomial(10, 0.3) | 3 | 2.1 | 1.4491 | np and np(1 − p) §3.4 |
3.1 · Generate the samples
# ================= Question 3: sampling distributions and the CLT =================
set.seed(123)
B <- 10000 # number of samples
n_vals <- c(30, 100, 500, 1000) # sample sizes
mu_x <- 0.5; sd_x <- sqrt(1 / 12) # Uniform(0, 1)
mu_y <- 3; sd_y <- sqrt(10 * 0.3 * 0.7) # Binomial(10, 0.3)
xbar <- list(); xsum <- list(); ybar <- list(); ysum <- list()
for (n in n_vals) {
key <- as.character(n)
X <- matrix(runif(B * n, min = 0, max = 1), nrow = B, ncol = n) # B samples of size n
Y <- matrix(rbinom(B * n, size = 10, prob = 0.3), nrow = B, ncol = n)
xbar[[key]] <- rowMeans(X); xsum[[key]] <- rowSums(X)
ybar[[key]] <- rowMeans(Y); ysum[[key]] <- rowSums(Y)
}
This is exactly Lab 3's loop, run twice per n. Each matrix has B = 10,000 rows (samples) and n columns (observations per sample), and rowMeans/rowSums turn each row into one X̄ and one Sn. At n = 1000 that's 10 million numbers per matrix. R handles it in about a second, so a short pause is normal.
3.2 · Examine the sampling distributions
# 3.2 simulated vs theoretical mean and SD
print(round(data.frame(n = n_vals,
mean_Xbar = sapply(xbar, mean), sd_Xbar = sapply(xbar, sd), sd_theory = sd_x / sqrt(n_vals),
mean_Xsum = sapply(xsum, mean), sd_Xsum = sapply(xsum, sd), sd_theory_sum = sd_x * sqrt(n_vals)), 4),
row.names = FALSE)
print(round(data.frame(n = n_vals,
mean_Ybar = sapply(ybar, mean), sd_Ybar = sapply(ybar, sd), sd_theory = sd_y / sqrt(n_vals),
mean_Ysum = sapply(ysum, mean), sd_Ysum = sapply(ysum, sd), sd_theory_sum = sd_y * sqrt(n_vals)), 4),
row.names = FALSE)
Output
n mean_Xbar sd_Xbar sd_theory mean_Xsum sd_Xsum sd_theory_sum
30 0.4999 0.0528 0.0527 14.9977 1.5825 1.5811
100 0.4997 0.0287 0.0289 49.9703 2.8658 2.8868
500 0.5000 0.0127 0.0129 249.9976 6.3747 6.4550
1000 0.5000 0.0092 0.0091 499.9641 9.1659 9.1287
n mean_Ybar sd_Ybar sd_theory mean_Ysum sd_Ysum sd_theory_sum
30 2.9961 0.2644 0.2646 89.8819 7.9315 7.9373
100 3.0002 0.1434 0.1449 300.0164 14.3450 14.4914
500 2.9991 0.0645 0.0648 1499.5455 32.2610 32.4037
1000 3.0004 0.0458 0.0458 3000.4466 45.8366 45.8258
What to writeReading the two tables
- Centres: the sample means average 0.5 (uniform) and 3 (binomial) at every n, matching E(X̄) = μ. The sums average nμ: 15, 50, 250, 500 and 90, 300, 1500, 3000.
- Spreads: every simulated SD is within about 1% of σ/√n (means) or σ√n (sums).
- The pattern: as n grows, the mean's distribution narrows around μ (uniform SD 0.053 → 0.009), while the sum's distribution widens (1.58 → 9.17) and its centre moves out to nμ. Relative to its own centre, though, the sum also gets more concentrated, since σ√n/(nμ) = σ/(μ√n) shrinks.
3.3 · CLT approximations against simulation
By hand, once, so the code isn't a black box. Take P(X̄30 > 0.52). By the CLT, X̄ ≈ N(0.5, σ2/n), with SD 0.2887/√30 = 0.05270. Then z = (0.52 − 0.5)/0.05270 = 0.38, so P ≈ 1 − Φ(0.38) = 1 − 0.6480 = 0.3520. For Ȳ30 > 3.1, the SD is 1.4491/√30 = 0.2646, z = 0.1/0.2646 = 0.38, and again ≈ 0.352. In R, each is one pnorm with the sampling SD as its sd:
# 3.3 CLT approximation vs simulated proportion
print(round(data.frame(n = n_vals,
X_CLT = 1 - pnorm(0.52, mean = mu_x, sd = sd_x / sqrt(n_vals)),
X_sim = sapply(xbar, function(v) mean(v > 0.52)),
Y_CLT = 1 - pnorm(3.1, mean = mu_y, sd = sd_y / sqrt(n_vals)),
Y_sim = sapply(ybar, function(v) mean(v > 3.1))), 4), row.names = FALSE)
Output
n X_CLT X_sim Y_CLT Y_sim 30 0.3522 0.3550 0.3527 0.3218 100 0.2442 0.2380 0.2451 0.2315 500 0.0607 0.0570 0.0614 0.0583 1000 0.0142 0.0161 0.0145 0.0145
How close is "close"? A simulated proportion from 10,000 samples has its own wobble of about √(p(1 − p)/10000) (the Q2.2 formula): roughly 0.005, 0.004, 0.002, 0.001 for the four rows. Measured against that:
- Uniform: agrees within noise at every n. The gaps of 0.003, 0.006, 0.004 and 0.002 are all within two wobbles.
- Binomial at n = 30 and 100: the CLT is off by much more than noise. 0.3527 against 0.3218 is a gap of 0.031, about six wobbles. Something real is going on.
The reason is that Ȳ is discrete. Each Y is a whole number, so the sum S30 is a whole number and Ȳ30 = S30/30 can only be 89/30, 90/30, 91/30, and so on. Now translate the event. Ȳ > 3.1 means S30 > 93, and for a whole number that means S30 ≥ 94. The value 93 itself, which is Ȳ = 3.1 exactly, is excluded. The plain CLT curve doesn't know this. It cuts at 93 and counts half of the probability bar at 93 as "above".
The fix is Module 3's continuity correction: cut at 93.5, halfway between the excluded and included values. That gives z = (93.5 − 90)/√63 = 3.5/7.937 = 0.44 and P ≈ 1 − Φ(0.44) = 0.330. The exact answer exists too, because a sum of independent Binomial(10, 0.3) variables is Binomial(300, 0.3): 1 - pbinom(93, 300, 0.3) = 0.3272. The simulation's 0.3218 is within about one wobble of it.
| n | Plain CLT | CLT + continuity correction | Exact | Simulated |
|---|---|---|---|---|
| 30 | 0.3527 | 0.3296 | 0.3272 | 0.3218 |
| 100 | 0.2451 | 0.2344 | 0.2337 | 0.2315 |
| 500 | 0.0614 | 0.0596 | 0.0599 | 0.0583 |
| 1000 | 0.0145 | 0.0141 | 0.0144 | 0.0145 |
The correction matters less as n grows. The half-step it fixes is 0.5/n on the Ȳ scale, which becomes tiny compared with the SD. At n = 1000 all four columns agree. The uniform needs no correction at all, because it's continuous.
Unpack: the optional R lines for the last two columns
Corrected: 1 - pnorm((floor(3.1*n_vals) + 0.5)/n_vals, mu_y, sd_y/sqrt(n_vals)). Exact: 1 - pbinom(floor(3.1*n_vals), 10*n_vals, 0.3). Exact works because adding n independent "successes in 10 trials" counts gives "successes in 10n trials" with the same p.
What to writeComparing the approximations with the simulation
- Uniform: the CLT values (0.3522, 0.2442, 0.0607, 0.0142) agree with the simulated proportions (0.3550, 0.2380, 0.0570, 0.0161) within simulation error at every n.
- Binomial: agreement is good at n = 500 and 1000, but at 30 and 100 the plain CLT overestimates by 0.03 and 0.014. That's because Ȳ is discrete: Ȳ30 > 3.1 means sum ≥ 94, and the normal curve wrongly counts part of the probability at sum = 93. A continuity correction removes most of the gap (0.3296 against 0.3218 simulated). The exact Binomial(10n, 0.3) answer confirms it.
- Both: the probabilities shrink fast as n grows (0.35 → 0.01). The thresholds 0.52 and 3.1 stay fixed while the sampling SD shrinks like 1/√n, so they move further into the tail (z goes from 0.38 to 2.19).
3.4 · Histograms with normal curves
# 3.4 histograms with normal curves (4 figures, 2 x 2 panels each)
# Binomial sums are whole numbers (and binomial means are multiples of 1/n), so their
# bin edges must sit halfway between possible values; otherwise the histogram shows a
# false comb pattern. `step` = gap between possible values (NULL for continuous data).
make_breaks <- function(v, step) {
if (is.null(step)) return(40)
w <- step * max(1, round(diff(range(v)) / step / 40)) # about 40 bins, whole steps wide
seq(min(v) - step / 2, max(v) + w, by = w)
}
plot_four <- function(samples, centre, spread, label, colour, step = function(n) NULL) {
par(mfrow = c(2, 2))
for (n in n_vals) {
v <- samples[[as.character(n)]]
hist(v, breaks = make_breaks(v, step(n)), freq = FALSE, col = colour, border = "white",
main = paste0(label, ", n = ", n), xlab = label)
curve(dnorm(x, centre(n), spread(n)), add = TRUE, col = "red", lwd = 2)
}
par(mfrow = c(1, 1))
}
plot_four(xbar, function(n) mu_x, function(n) sd_x / sqrt(n), "Uniform: sample mean", "steelblue")
plot_four(xsum, function(n) n * mu_x, function(n) sd_x * sqrt(n), "Uniform: sample sum", "darkcyan")
plot_four(ybar, function(n) mu_y, function(n) sd_y / sqrt(n), "Binomial: sample mean", "steelblue",
step = function(n) 1 / n)
plot_four(ysum, function(n) n * mu_y, function(n) sd_y * sqrt(n), "Binomial: sample sum", "darkcyan",
step = function(n) 1)
Two helpers keep this short. plot_four draws one 2 × 2 figure (one panel per n) and is called four times: uniform mean, uniform sum, binomial mean, binomial sum. Its centre and spread arguments are small functions of n, so the same code overlays N(μ, σ2/n) on means and N(nμ, nσ2) on sums. The red curve's sd is σ/√n or σ√n, never a variance. make_breaks only matters for the binomial. It's explained in the trap below.
These are the histograms your R code draws (bin heights from the actual run, with the normal curve computed on top). Switch between the four figures. Each panel zooms to its own range, the way R's does, so read the axis numbers: that's where the narrowing (means) and widening (sums) show.
With R's plain breaks = 40, the binomial-mean histogram at n = 30 comes out as a comb: tall bars alternating with short ones, which looks like the CLT failing. It isn't. Ȳ30 can only take values 1/30 = 0.033 apart, and bins 0.05 wide hold one possible value or two, alternately. At n = 100 the possible values fall exactly on the bin edges, which shifts every bar half a bin to the left of the curve. The cure is to put the bin edges halfway between possible values, with widths that are whole multiples of the step. That's all make_breaks does (step = 1 for sums, 1/n for means). If you'd rather keep the code simpler, plain breaks = 40 is fine for the uniform, and you can explain the comb in one sentence instead. Either earns the "discuss" marks.
What to writeDiscuss how the distributions approach normality
- Every histogram is bell-shaped and sits on its CLT curve, for both populations, for means and sums, from n = 30 on.
- The uniform is symmetric to begin with, so its means look normal even for very small n (at n = 30 the simulated skewness is 0.002). Across our sizes the visible change is the spread: the mean's SD falls from 0.053 to 0.009 while the sum's grows from 1.6 to 9.2.
- The binomial starts out skewed (one Y has skewness (1 − 2p)/σ = 0.4/1.449 = 0.28) and lumpy (whole numbers only). Averaging shrinks the skewness like 0.28/√n, to 0.05 at n = 30 and 0.009 at 1000. The lumpiness fades as the possible values get closer together relative to the spread. That's why the Q3.3 probabilities needed a continuity correction at small n but not at large n.
- Mean and sum always share a shape, because Sn = nX̄. Only the centre (μ against nμ) and the scale change.
- Conclusion: the Central Limit Theorem holds. Whatever the population's shape, the sampling distributions of X̄ and Sn approach N(μ, σ2/n) and N(nμ, nσ2). The approach is faster for a symmetric population (uniform) than a skewed or discrete one (binomial).
Check yourself: the question's smallest n is 30, so everything already looks normal. How could you show the approach to normality more convincingly, if you wanted to?
Add a small n such as 1, 2 or 5, where the starting shape is still visible. Change n_vals to c(1, 5, 30, 100) for one extra figure, or drive the widget on the Lab 3 page. At n = 1 the uniform histogram is flat and the binomial is the lumpy, skewed pmf itself. Keep the required sizes too: an extra figure is a bonus, not a replacement.
4 · Turning it into the PDF
The instructions want a typed PDF containing all R code, all figures and the relevant outputs, with your name, ID number and lecture section in the top-right corner of page 1. Handwritten or scanned work isn't accepted. The simplest route:
- Open a Google Doc (or Word). Put name, ID and lecture section top right, then a title.
- Per question part, add a heading (e.g. "Q1.3 IQR and outliers"), then:
- the code for that part, pasted from your script in a monospace font (Courier New or Consolas, 9–10 pt) so the alignment survives;
- the console output, pasted the same way;
- the figure. In RStudio's Plots pane, Export → Save as Image… (PNG, about 1000 × 750), then insert the image;
- your answer in two to five sentences of your own.
- Export: File → Download → PDF (Google Docs) or File → Save As → PDF (Word). Open the PDF and check that every figure is there and readable. Then upload it to your own lecture section's Classroom, after accepting its invitation.
Unpack: the R Markdown route, if you're curious
RStudio's File → New File → R Markdown… mixes text and code chunks, and Knit runs them and builds a document with every output and figure already placed. Knit to Word, then save as PDF. It's neater, but it means learning a new tool the night before a deadline, so it's optional.
Six figures in all: the Q1 2 × 2, the Q2.1 three-panel, and four Q3 figures. Q2.2 is numbers only.
5 · The complete script
All of the above in one file (154 lines), in the order the questions ask. It runs top to bottom in a fresh R session in a few seconds. Use it to compare against your own, not to replace it.
Run it in one go: in the R app, save it as lab-assignment.R in Documents and type source("~/Documents/lab-assignment.R") in the console. In RStudio, click Source. The dev.new() before each figure opens it in its own window, so you get six plot windows and no figure replaces another. If some seem missing, they may be stacked behind the console; the R app's Window menu lists them all. RStudio shows them in its Plots pane, and the ← → arrows step through them. To put a figure in your report, click its window, then use Edit → Copy and paste into the Doc.
Show the complete script
# MATH U113 Lab Assignment: R code (base R only, no packages needed)
# ================= Question 1: iris =================
data(iris)
sl <- iris$Sepal.Length
pl <- iris$Petal.Length
get_modes <- function(x) { # base R has no mode function
counts <- table(x)
as.numeric(names(counts)[counts == max(counts)])
}
# 1.1 measures of centre and spread
stats <- data.frame(
variable = c("Sepal.Length", "Petal.Length"),
mean = c(mean(sl), mean(pl)),
median = c(median(sl), median(pl)),
mode = c(paste(get_modes(sl), collapse = ", "),
paste(get_modes(pl), collapse = ", ")),
variance = c(var(sl), var(pl)),
sd = c(sd(sl), sd(pl))
)
print(stats, digits = 4)
# species-wise means and SDs
print(aggregate(cbind(Sepal.Length, Petal.Length) ~ Species, data = iris, FUN = mean))
print(aggregate(cbind(Sepal.Length, Petal.Length) ~ Species, data = iris, FUN = sd))
# 1.2 five-number summaries and percentiles
print(fivenum(sl))
print(fivenum(pl))
print(quantile(sl, probs = c(0.12, 0.60, 0.90)))
# 1.3 IQR and the 1.5 x IQR rule
iqr_sl <- IQR(sl)
q_sl <- quantile(sl, c(0.25, 0.75))
lower <- q_sl[1] - 1.5 * iqr_sl
upper <- q_sl[2] + 1.5 * iqr_sl
cat("IQR of Sepal.Length:", iqr_sl, "\n")
cat("Fences:", lower, "to", upper, "\n")
cat("Outliers:", sl[sl < lower | sl > upper], "\n") # prints nothing if none
cat("IQR of Petal.Length:", IQR(pl), "\n")
# 1.4 histograms and boxplots
dev.new() # each figure opens in its own window
par(mfrow = c(2, 2))
hist(sl, col = "steelblue", border = "white",
main = "Histogram of Sepal Length", xlab = "Sepal length (cm)", ylab = "Frequency")
hist(pl, col = "darkcyan", border = "white",
main = "Histogram of Petal Length", xlab = "Petal length (cm)", ylab = "Frequency")
boxplot(sl, horizontal = TRUE, col = "steelblue",
main = "Boxplot of Sepal Length", xlab = "Sepal length (cm)")
boxplot(pl, horizontal = TRUE, col = "darkcyan",
main = "Boxplot of Petal Length", xlab = "Petal length (cm)")
par(mfrow = c(1, 1))
# ================= Question 2.1: Binomial(n, 5/n) vs Poisson(5) =================
set.seed(123)
N <- 10000
n_vals <- c(20, 100, 500)
k <- 0:15
dev.new()
par(mfrow = c(1, 3))
for (n in n_vals) {
x <- rbinom(N, size = n, prob = 5 / n)
sim_p <- sapply(k, function(j) mean(x == j)) # simulated P(X = j)
plot(k - 0.15, sim_p, type = "h", lwd = 4, col = "steelblue",
ylim = c(0, 0.22), xlab = "k", ylab = "Probability",
main = paste0("Binomial(", n, ", 5/", n, ") vs Poisson(5)"))
points(k + 0.15, dpois(k, 5), type = "h", lwd = 4, col = "red")
legend("topright", c("simulated binomial", "Poisson(5)"),
col = c("steelblue", "red"), lwd = 4, bty = "n")
cat("n =", n, " sample mean =", mean(x), " sample var =", round(var(x), 4),
" max|sim - Poisson| =", round(max(abs(sim_p - dpois(k, 5))), 4),
" max|exact binom - Poisson| =", round(max(abs(dbinom(k, n, 5/n) - dpois(k, 5))), 4), "\n")
}
par(mfrow = c(1, 1))
# ================= Question 2.2: exponential lifetimes, mean 4 years =================
p_true <- 1 - pexp(6, rate = 1/4) # = exp(-1.5)
cat("Theoretical P(X > 6) =", p_true, "\n")
set.seed(123)
for (n in c(100, 1000, 10000)) {
life <- rexp(n, rate = 1/4)
est <- mean(life > 6)
cat("n =", n, " estimate =", est, " abs error =", round(abs(est - p_true), 4), "\n")
}
# typical error: repeat each experiment 1000 times
set.seed(123)
for (n in c(100, 1000, 10000)) {
ests <- replicate(1000, mean(rexp(n, rate = 1/4) > 6))
cat("n =", n, " SD of 1000 estimates =", round(sd(ests), 4),
" theory sqrt(p(1-p)/n) =", round(sqrt(p_true * (1 - p_true) / n), 4), "\n")
}
# ================= Question 3: sampling distributions and the CLT =================
set.seed(123)
B <- 10000 # number of samples
n_vals <- c(30, 100, 500, 1000) # sample sizes
mu_x <- 0.5; sd_x <- sqrt(1 / 12) # Uniform(0, 1)
mu_y <- 3; sd_y <- sqrt(10 * 0.3 * 0.7) # Binomial(10, 0.3)
xbar <- list(); xsum <- list(); ybar <- list(); ysum <- list()
for (n in n_vals) {
key <- as.character(n)
X <- matrix(runif(B * n, min = 0, max = 1), nrow = B, ncol = n) # B samples of size n
Y <- matrix(rbinom(B * n, size = 10, prob = 0.3), nrow = B, ncol = n)
xbar[[key]] <- rowMeans(X); xsum[[key]] <- rowSums(X)
ybar[[key]] <- rowMeans(Y); ysum[[key]] <- rowSums(Y)
}
# 3.2 simulated vs theoretical mean and SD
print(round(data.frame(n = n_vals,
mean_Xbar = sapply(xbar, mean), sd_Xbar = sapply(xbar, sd), sd_theory = sd_x / sqrt(n_vals),
mean_Xsum = sapply(xsum, mean), sd_Xsum = sapply(xsum, sd), sd_theory_sum = sd_x * sqrt(n_vals)), 4),
row.names = FALSE)
print(round(data.frame(n = n_vals,
mean_Ybar = sapply(ybar, mean), sd_Ybar = sapply(ybar, sd), sd_theory = sd_y / sqrt(n_vals),
mean_Ysum = sapply(ysum, mean), sd_Ysum = sapply(ysum, sd), sd_theory_sum = sd_y * sqrt(n_vals)), 4),
row.names = FALSE)
# 3.3 CLT approximation vs simulated proportion
print(round(data.frame(n = n_vals,
X_CLT = 1 - pnorm(0.52, mean = mu_x, sd = sd_x / sqrt(n_vals)),
X_sim = sapply(xbar, function(v) mean(v > 0.52)),
Y_CLT = 1 - pnorm(3.1, mean = mu_y, sd = sd_y / sqrt(n_vals)),
Y_sim = sapply(ybar, function(v) mean(v > 3.1))), 4), row.names = FALSE)
# 3.4 histograms with normal curves (4 figures, 2 x 2 panels each)
# Binomial sums are whole numbers (and binomial means are multiples of 1/n), so their
# bin edges must sit halfway between possible values; otherwise the histogram shows a
# false comb pattern. `step` = gap between possible values (NULL for continuous data).
make_breaks <- function(v, step) {
if (is.null(step)) return(40)
w <- step * max(1, round(diff(range(v)) / step / 40)) # about 40 bins, whole steps wide
seq(min(v) - step / 2, max(v) + w, by = w)
}
plot_four <- function(samples, centre, spread, label, colour, step = function(n) NULL) {
dev.new()
par(mfrow = c(2, 2))
for (n in n_vals) {
v <- samples[[as.character(n)]]
hist(v, breaks = make_breaks(v, step(n)), freq = FALSE, col = colour, border = "white",
main = paste0(label, ", n = ", n), xlab = label)
curve(dnorm(x, centre(n), spread(n)), add = TRUE, col = "red", lwd = 2)
}
par(mfrow = c(1, 1))
}
plot_four(xbar, function(n) mu_x, function(n) sd_x / sqrt(n), "Uniform: sample mean", "steelblue")
plot_four(xsum, function(n) n * mu_x, function(n) sd_x * sqrt(n), "Uniform: sample sum", "darkcyan")
plot_four(ybar, function(n) mu_y, function(n) sd_y / sqrt(n), "Binomial: sample mean", "steelblue",
step = function(n) 1 / n)
plot_four(ysum, function(n) n * mu_y, function(n) sd_y * sqrt(n), "Binomial: sample sum", "darkcyan",
step = function(n) 1)
1) mode() returns the data type ("numeric"), not the statistical mode. Use get_modes, and report both modes for Petal.Length. 2) "Distinguishes" justified by the means alone, with no within-species spread (1.1). 3) rexp(n, 4) for "mean 4". The rate is 1/4, and rexp(n, 4) gives lifetimes averaging three months. 4) pnorm(0.52, 0.5, 1/12), passing the population variance as sd, instead of the sampling SD sqrt(1/12)/sqrt(n). 5) Concluding "the CLT fails for the binomial at n = 30" from the 0.35 vs 0.32 gap or from a comb-shaped histogram. Both come from discreteness, not from the CLT. 6) A figure without titles or axis labels, which is an explicitly requested mark.
Your minimal prerequisite kit for this assignment
- Lab 1's toolkit: mean, median, mode,
var/sd(both divide by n − 1), quartiles, boxplots, and the 1.5 × IQR rule (descriptive statistics notes). - Lab 2's naming scheme:
r/d/p+binom/pois/exp/norm, with rate (not mean) for the exponential and SD (not variance) for the normal (Lab 2 page). - Lab 3's two facts plus the CLT: X̄ has mean μ and SD σ/√n, and is approximately normal for large n (Lab 3 page).
- Mean and variance of the uniform ((a + b)/2, (b − a)2/12) and the binomial (np, np(1 − p)).
- Continuity correction: a discrete "> 93" becomes "> 93.5" before using the normal curve (Module 3).
What to practise
| Skill | Where | How many |
|---|---|---|
| Run each question's code and match its output to this page, digit for digit | §1–3 above | 3 sittings |
Redo Q1 for Sepal.Width and Petal.Width without looking. Which one separates the species? | iris | 1 run |
| Redo Q2.1 with λ = 2 instead of 5 and predict the variances first | Q2.1 code | 1 run |
CLT probabilities by hand, checked with pnorm | Devore §5.4 odd exercises | 4 |
These are for after submission. They're the best preparation for an open-book R lab exam, if one is set.
"I'm doing a base-R assignment for a first probability course (Devore 9th ed.). Here is my code for [part] and the error or output I get: [paste]. Explain what is wrong in my code without rewriting the whole thing, and without using packages or the tidyverse."
"Here is my 3-sentence answer to 'which variable better distinguishes the three iris species, justified by species-wise means': [paste]. Tell me what a strict grader would say is missing. Don't write a replacement answer."
Both prompts keep the work yours: the AI points out problems, and you fix them.