0% found this document useful (0 votes)
28 views7 pages

Sampling Distributions & R Simulations

The lecture plan focuses on understanding sampling distributions and their simulation in R, emphasizing the behavior of sample statistics like mean and variance. It covers the Central Limit Theorem and the distribution of sample variances, including practical R simulation steps and diagnostics to verify theoretical results. Prerequisites include a basic understanding of Normal, Poisson, and Chi-Square distributions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views7 pages

Sampling Distributions & R Simulations

The lecture plan focuses on understanding sampling distributions and their simulation in R, emphasizing the behavior of sample statistics like mean and variance. It covers the Central Limit Theorem and the distribution of sample variances, including practical R simulation steps and diagnostics to verify theoretical results. Prerequisites include a basic understanding of Normal, Poisson, and Chi-Square distributions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lecture Plan: Sampling Distributions & Simulation in R

Objective: To understand how sample statistics (like the mean and variance) behave when we
take repeated samples from a population, and how to verify these theoretical results using R
simulations.

Prerequisites: Basic understanding of Normal, Poisson, and Chi-Square distributions.

Part 1: Lecture Notes


1. Introduction: What is a Sampling Distribution?
●​ Intuition: Imagine you are cooking a giant pot of soup (the Population). You taste one
spoonful (a Sample).
○​ If you take 1,000 different spoonfuls and measure the saltiness of each one, the list
of those 1,000 measurements forms a Sampling Distribution.
●​ Why it matters: We rarely see the whole population. We only see one sample. Sampling
distributions tell us how confident we can be that our one sample is close to the truth.

2. The Central Limit Theorem (CLT) & Sample Means


Reference: CS1B_Example_0601_V01.R

The Theory:
Even if the population is not Normal (e.g., it is Poisson, Skewed, etc.), the distribution of the
Sample Means X-bar will become approximately Normal as the sample size (n) gets larger.
The Scenario (from Example 0601):
●​ Population: Daily insurance claims follow a Poisson distribution with mean \lambda = 5.
●​ Sample: We observe claims for 40 days (n=40).
●​ Transformation: We standardize the means to see if they fit a Standard Normal N(0,1)
distribution.​

X-bar ~ N(Mu, Sigma^2/n)


~ N(0,1)
R Simulation Steps:
1.​ Simulate: Generate 1,000 samples of 40 days each from a Poisson(5).
2.​ Calculate: Compute the mean for each of the 1,000 samples.
3.​ Standardize: Convert these means into Z-scores.
4.​ Verify: Check if these Z-scores look like a standard Normal Bell curve.

Instructor Note: Emphasize that the original data is discrete (counts 0, 1, 2...), but the
average of those counts becomes continuous and bell-shaped.

3. Sampling Distribution of the Variance

Reference: Exercise 6.01, CS1B_Ch_06_Exercises.pdf & CS1B_Exercise_0601_V01.R

The Theory:

Unlike means, sample variances (S^2) do not look Normal. Variances are squared distances, so
they are always positive and typically skewed to the right.

If the underlying population is Normal N(\mu, \sigma^2), the transformed sample variance
follows a Chi-Squared distribution:

The Scenario (from Exercise 6.01):


●​ Population: Heights of women are N(162, 9^2) (Mean 162cm, SD 9cm)2.​
●​ Sample: We measure n=20 women.
●​ Transformation: We calculate the sample variance S^2 and transform it to \frac{19 \times
S^2}{81}.
●​ Expectation: This should look like a Chi-Squared distribution with 20-1 = 19 degrees of
freedom3.​

R Simulation Steps:
1.​ Loop: Run 1,000 simulations of 20 women.
2.​ Store: Save the sample variance of each group.
3.​ Transform: Multiply variances by (n-1)/\sigma^2.
4.​ Verify: Compare against the theoretical \chi^2_{19} curve.

4. Diagnostics: How to "Prove" the Fit in R

We use four main tools to check if our simulation matches the theory. Use the consolidated
script to demonstrate these live.

A. Visual Inspection (Histogram vs Density)


●​ Plot the histogram of your simulated data.
●​ Overlay the theoretical "true" PDF (Red dashed lines in the script).
●​ Observation from Exercise 6.01: The simulated peak is slightly to the left, but the shape is
generally close to the Chi-square curve4.​

B. Moment Matching (Mean & Variance)


●​ Calculate the mean and variance of your vector X.
●​ Compare to theoretical \chi^2_{df} mean (df) and variance (2 \times df).
●​ Result: For Exercise 6.01, Simulated Mean \approx 18.89 vs True Mean 19. Simulated Var
\approx 37.6 vs True Var 38. This confirms accuracy5.​

C. Quantile Comparison
●​ Compare the Median, Q1 (25%), and Q3 (75%).
●​ Result: In the exercise, the simulated quartiles were slightly lower than the true values
(e.g., Median 18.13 vs 18.33), suggesting slight random variation, but very close 6.​

D. QQ Plots (Quantile-Quantile)
●​ Intuition: A QQ plot graphs the expected value (if the theory were perfect) against the
observed value.
●​ Ideal: A perfect straight diagonal line.
●​ Interpretation:
○​ If tails curl away from the line, you have "heavy" or "light" tails.
○​ In the Exercise 6.01 QQ plot, the points lie largely on the line, though slightly weaker
at the tails, confirming the data is not skewed away from the distribution7.​

Part 2: Consolidated R Script

This script merges the logic from both provided files into a single teaching flow. I have added
comments to guide the lecture.

# ==============================================================================​
# LECTURE: SAMPLING DISTRIBUTIONS​
# Part 1: Central Limit Theorem (Means)​
# Part 2: Distribution of Sample Variances (Chi-Square)​
# ==============================================================================​

# ==============================================================================​
# PART 1: THE CENTRAL LIMIT THEOREM (CLT)​
# Source: CS1B_Example_0601_V01.R​
# Scenario: Claims occur as Poisson(mean=5). We take samples of n=40 days.​
# ==============================================================================​

# 1. Setup Parameters​
m <- 5 # True Mean (lambda)​
n <- 40 # Sample Size​

# 2. Simulation Loop​
# We want to see the distribution of the MEAN of these samples.​
xbar <- rep(0, 1000)​
[Link](23)​

for (i in 1:1000) {​
x <- rpois(n, m) # Generate 40 days of Poisson data​
xbar[i] <- mean(x) # Store the average claims for those 40 days​
}​

# 3. Standardization​
# CLT says: xbar ~ N(m, m/n). Let's standardize to Z ~ N(0,1)​
# Z = (sample_mean - true_mean) / standard_error​
Z <- (xbar - m) / sqrt(m/n)​

# 4. Visualization (Histogram vs Normal Curve)​
par(mfrow=c(1,1)) # Reset plot window​
hist(Z, prob=TRUE, ​
xlab="Standardised Sample Means", ​
main="CLT in Action: Poisson -> Normal", ​
col="lightblue", ylim=c(0, 0.5))​

# Add the empirical density (what our simulation looks like)​
lines(density(Z), col="blue", lwd=2)​

# Add the theoretical Normal PDF (what the math predicts)​
xvals <- seq(-4, 4, by=0.01)​
lines(xvals, dnorm(xvals, 0, 1), lwd=2, lty=2, col="red")​
legend("topright", legend=c("Simulated", "Theoretical N(0,1)"), ​
col=c("blue", "red"), lty=c(1,2), lwd=2)​

# 5. Diagnostic: QQ Plot​
# Are the tails behaving?​
[Link]() # Open new window for clarity​
qqnorm(Z, main="QQ Plot for CLT Example")​
qqline(Z, lty=2, col="red", lwd=2)​

# 6. Empirical Probabilities​
# Check P(Z > 1.5). Theory says N(0,1) probability is approx 0.0668​
prob_sim <- length(Z[Z > 1.5]) / length(Z)​
prob_true <- pnorm(1.5, 0, 1, lower=FALSE)​

cat("\n--- PART 1 RESULTS ---\n")​
cat("Simulated P(Z > 1.5):", prob_sim, "\n")​
cat("Theoretical P(Z > 1.5):", prob_true, "\n")​


# ==============================================================================​
# PART 2: SAMPLING DISTRIBUTION OF THE VARIANCE​
# Source: CS1B_Ch_06_Exercises.pdf & CS1B_Exercise_0601_V01.R​
# Scenario: Heights are N(162, 9^2). We take samples of n=20 women.​
# Theory: (n-1)S^2 / sigma^2 ~ Chi-Squared(n-1)​
# ==============================================================================​

# 1. Setup Parameters​
mu <- 162​
sigma <- 9​
n_w <- 20 # Sample size for women​
df <- n_w - 1 # Degrees of freedom (19)​

# 2. Simulation Loop​
xvar <- rep(0, 1000)​
[Link](27)​

for (i in 1:1000) {​
# Generate 20 heights from Normal Dist​
x <- rnorm(n_w, mu, sigma) ​
# Store the sample VARIANCE​
xvar[i] <- var(x) ​
}​

# 3. Transformation​
# Convert sample variance to Chi-Square scale​
X_vec <- (df * xvar) / sigma^2​

# 4. Visualization​
# Note: Chi-square is not symmetric like the Normal curve!​
[Link]()​
hist(X_vec, prob=TRUE, ​
xlab=expression((n-1)*S^2 / sigma^2), ​
main="Distribution of Sample Variances", ​
xlim=c(0, 50), ylim=c(0, 0.07), col="lightgreen")​

# Empirical Density​
lines(density(X_vec), col="blue", lwd=2)​

# Theoretical Chi-Squared PDF​
xvals_chi <- seq(0, 50, by=0.1)​
lines(xvals_chi, dchisq(xvals_chi, df), lwd=2, lty=2, col="red")​
legend("topright", legend=c("Simulated", "True Chi-Sq(19)"), ​
col=c("blue", "red"), lty=c(1,2), lwd=2)​

# 5. Moments Comparison (Mean and Variance)​
cat("\n--- PART 2 RESULTS ---\n")​
cat("Simulated Mean:", mean(X_vec), " | Theoretical Mean (df):", df, "\n")​
cat("Simulated Var :", var(X_vec), " | Theoretical Var (2*df):", 2*df, "\n")​

# 6. Quantiles Comparison​
# Let's check the Median and IQR​
sim_quantiles <- quantile(X_vec, c(0.25, 0.5, 0.75))​
true_quantiles <- qchisq(c(0.25, 0.5, 0.75), df)​

print("Simulated Quantiles:")​
print(sim_quantiles)​
print("True Chi-Squared Quantiles:")​
print(true_quantiles)​

# 7. Diagnostic: QQ Plot vs Chi-Squared Distribution​
# We generate a 'perfect' theoretical set to compare against​
chi_theoretical <- rchisq(1000, df)​

[Link]()​
qqplot(chi_theoretical, X_vec, ​
main="QQ Plot: Sample Variance vs Chi-Squared",​
xlab="Theoretical Chi-Squared Quantiles",​
ylab="Simulated Sample Variances")​
abline(0, 1, lty=2, col="red", lwd=2)​

# 8. Probability Check​
# Calculate P(X > 15)​
prob_chi_sim <- length(X_vec[X_vec > 15]) / length(X_vec)​
prob_chi_true <- pchisq(15, df, lower=FALSE)​

cat("Simulated P(X > 15):", prob_chi_sim, "\n")​
cat("True P(X > 15) :", prob_chi_true, "\n")​
cat("Conclusion: Empirical result is slightly smaller (approx 2.5% error)\n")​

Common questions

Powered by AI

Transforming sample variances into a Chi-Square scale involves taking the variances from repeated samples, multiplying them by the factor (n-1)/sigma^2, where n is the sample size and sigma is the population standard deviation. This transformation aligns the sample variances with a Chi-Square distribution. Validation occurs through visualization using histograms and theoretical Chi-Squared PDFs, combined with statistical measures like comparing means, variances, and using QQ plots for a quantile-quantile comparison to assess the fit with Chi-Squared expectations .

In R, the simulation of sample means involves iterating over repeated random sampling from a specified distribution and calculating the means of these samples. Standardization transforms these means into Z-scores to fit a Standard Normal distribution. The steps include: 1) generating Poisson data (e.g., 1,000 samples of 40 days each), 2) storing the means of these samples, 3) standardizing these means by subtracting the population mean and dividing by the standard error, and 4) visualizing them with a histogram overlaid with the theoretical Normal PDF to confirm bell curve shapes .

Unlike sample means, sample variances do not follow a Normal distribution but are inherently positive and typically skewed. If the population is Normal, the sample variance follows a Chi-Squared distribution. R simulations demonstrate this by taking multiple samples from a Normal distribution, calculating their variances, transforming these to fit a Chi-Squared distribution by multiplying by (n-1)/sigma^2, and visually comparing them using histograms and theoretical Chi-Squared Probability Density Functions (PDFs). Additional diagnostics include moment matching and QQ plots to confirm the fit against theoretical expectations .

Empirical probabilities from simulations sometimes deviate slightly from theoretical values due to random error inherent in finite sampling. These deviations are generally small and within acceptable error margins, validating the simulation's accuracy and robustness. For instance, calculating the probability P(X > 15) for sample variances using a Chi-Square distribution simulation demonstrates approximately a 2.5% error compared to theoretical expectations. This small deviation suggests the R simulation effectively captures theoretical behavior, notwithstanding minor stochastic variability .

Moment matching compares the calculated moments (mean and variance) of the simulated data against theoretical values expected from the distribution. For instance, for a Chi-Squared distribution with k degrees of freedom, the expected mean is k and the variance is 2k. During simulations in R, the means and variances from the simulated data are calculated and checked against these theoretical moments. Exercise 6.01 illustrates this by showing a simulated mean of approximately 18.89 compared to the true mean of 19, and a simulated variance of about 37.6 compared to the true variance of 38, confirming the accuracy of simulation .

QQ plots graph the quantiles of observed data (from simulations) against the expected quantiles if the data followed a perfect theoretical distribution. A straight diagonal line through the QQ plot indicates close agreement between the two sets. Deviations from this line suggest departures from the expected distribution, such as heavy or light tails if the points curl away from the line. In Exercise 6.01, the QQ plot of simulated sample variances shows points lying largely on the line, confirming the data is aligned with a Chi-Squared distribution, although there is slight deviation at the tails .

The Central Limit Theorem (CLT) states that the distribution of the sample means becomes approximately Normal, even if the underlying population distribution is not Normal, as the sample size (n) increases. In R, this principle can be demonstrated by simulating multiple samples and calculating their means. For instance, by simulating 1,000 samples of size 40 from a Poisson distribution with mean 5, standardizing these sample means can show whether they fit a Standard Normal N(0,1) distribution. The simulation steps include generating sample data, calculating means, standardizing them to Z-scores, and then visually verifying them against a Normal distribution using histograms and QQ plots .

Visual inspection techniques involve plotting the histogram of simulated data and overlaying the theoretical true Probability Density Function (PDF) on the same graph. This allows for direct comparison of the shape and spread of the simulated data to the established theoretical distribution. For instance, in Exercise 6.01, the simulated data is compared to the Chi-Square curve by plotting the histogram and the Chi-Square PDF, observing that the peak of the simulated data may slightly deviate from the theoretical curve, but the shape is generally close .

Empirical probabilities are determined by counting occurrences within simulated data that meet a certain condition and dividing this count by the total number of simulations. This fraction represents the empirical probability. Theoretical probabilities are calculated using formulas for the respective distribution. In R, for the normal distribution in the context of sampling means, one may calculate the probability that a Z-score exceeds 1.5, for example, and compare it with theoretical expectations using pnorm to confirm accuracy. This method shows how closely simulated results align with theoretical predictions, such as a small percent error indicating a good fit .

Comparing quantiles involves checking if specific quantiles (like the median, Q1, and Q3) of the simulated data are close to those of the theoretical distribution. In the Chi-Squared distribution case, this comparison helps identify how well the simulated data aligns with the theoretical distribution. In Exercise 6.01, the simulated quartiles were slightly lower than the true values, indicating some random variation but overall closeness to the expected distribution, which confirms that the simulated sampling variances generally follow the expected Chi-Squared behavior .

You might also like