Welcome & Setup
Resource Welcome to Posit Cloud(formerly RStudio.cloud) — your browser‑based workspace.
Why this setup?
- No installs. Everything runs in your web browser.
- Integrated notes + code. Write, run, and explain in one place using Quarto
.qmdfiles. - Great for open‑notes. Your
.qmdbecomes a dynamic study sheet for quizzes, tests, and the final project.
Important Tip: We only use RStudio here (ignore Jupyter). Thefree plan is enough — no premium subscription needed.
The Ideal `.qmd` Notes Workflow
Not sure how to comfortably mix math, English, and R code? Follow this 3-step beginner blueprint:
Outside of any grey boxes, just type normally! "Here is Problem 4. I know the population standard deviation, so I must use a Z-interval."
```{r}
# Only R code goes inside these grey boxes!
```
Click the 🧶 Render button at the top of your script to magically turn your messy workspace into a clean HTML or PDF study guide!
Type posit.cloud → open project → File → New File → Quarto Document…
Step 1 — Create your free Posit Cloud account
- Open posit.cloud and clickSign Up.
- Use Continue with Google (easy) or create an email+password account.
- If prompted, verify your email, then use Log In for future visits.
Step 2 — Start a new RStudio project
- From Your Workspace, click New Project → New RStudio Project (not Jupyter).
- Wait for Deploying Project… to finish. Rename the project at the top (e.g., MATH 1320 —HW Workspace) to keep things organized.
Step 3 — Open a Quarto .qmd file
- Go to File → New File → Quarto Document….
- Enter a meaningful Title (e.g., My First Quarto Document) and choose an output format: PDF (preferred), HTML, or Word. ClickCreate.
- Watch out: On first use, Posit Cloud may show a yellow banner asking to Installitems (TinyTeX/LaTeX, packages). Click Install and let the Console finish — you don’t need to type anything.
Step 4 — Render (build) your document
- Click the blue Render button at the top of the editor pane.
- If prompted for format, choose PDF. If PDF errors the first time, pickHTML for now; we can configure PDF later.
Step 5 — Save, rename, and submit
- Save often:Ctrl+S (Windows) or Cmd+S(Mac), or File → Save.
- Find your output (e.g.,
HW01.pdforHW01.html) in theFiles pane. - Rename for submission: check the file → More →Rename… → use
Lastname_Firstname_HW01.pdf(e.g.,Kodipelly_Vinay_HW01.pdf), then More → Export… /Download.
Practice: Open the sample lecture project and make a permanent copy:
- Visit posit.cloud/content/10744018 (log in if needed).
- Click Save a Permanent Copy (top‑right) to clone it into Your Workspace.
- Open the
.qmdin the Files pane. If a yellow banner asks toInstall, click it and wait. - Click Render (PDF preferred; HTML/Word are acceptable if PDF isn’t ready yet).
We’ll repeat this after every lecture so you always have your own permanent copy.
Basic Quarto structure
---
title: "My Quarto Document"
format: pdf
---
# Introduction
This is an introduction to my analysis.
## Code Chunk Example
```{r}
# A basic R calculation
x <- 1:5
mean(x)
```
# Conclusion
Summary of findings.
Pro Tip: Render frequently to catch errors early. Use the Render button in RStudio.
Chapters 1–3: Descriptive Statistics & Data Exploration
Foundation Summary measures and quick EDA.
First commands to try
# Very first commands to try in R
x <- c(2, 5, 7, 9) # store data
length(x) # how many values?
mean(x) # average
sd(x) # standard deviation
sort(x) # sort values
table(x) # frequency table
runif(5) # 5 random numbers between 0 and 1
sample(1:10, 3) # 3 random integers from 1 to 10 (no replacement)
Core R Commands (Data & Calculator)
# Storing data
x <- c(100, 200, 300, 400) # c() stands for "combine" or "concatenate"
x = c(100, 200, 300, 400) # same as above
x = 1:100 # shorthand: 1, 2, 3, ..., 100
# Miscellaneous helpers
sort(x) # sort data
length(x) # number of points (sample size)
sum(x) # sum of values
y <- c(1, 2, 3, 4)
x * y # elementwise products of two lists of equal length
table(x) # frequency table
stem(x) # stem-and-leaf plot
format(12345.678, scientific = FALSE) # force decimal format
# Generating random numbers
runif(5, 0, 3) # 5 real numbers from Uniform(0, 3)
runif(5) # 5 real numbers from Uniform(0, 1)
sample(1:1000, 10) # 10 integers from 1 to 1000 (without replacement)
sample(1:1000, 10, replace = TRUE) # with replacement
# Using R as a calculator
2 + 3; 7 - 4; 6 * 5; 8 / 2 # basic arithmetic
2^3 # exponentiation (2 to the 3rd power)
sqrt(9) # square root
abs(-3) # absolute value
factorial(4) # 4! = 4*3*2*1
choose(10, 3) # C(10,3) = 120
choose(10, 3) * factorial(3) # P(10,3) = 720
Numerical Summaries
Key formulas:
$$\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i$$
$$s^2 = \frac{\sum_{i=1}^{n} (x_i - \bar{x})^2}{n-1}, \qquad s = \sqrt{s^2}$$
$$\text{IQR} = Q_3 - Q_1$$
# Vector of data
x <- c(22, 25, 30, 28, 26, 31, 29, 27)
mean(x); median(x); sd(x); var(x); length(x)
quantile(x, probs = c(.25, .5, .75))
IQR(x)
summary(x)Tabular & Graphical
Example Scenario: Building the Matrix
"A survey of 200 students asks if they prefer Morning or Evening classes and if they are Undergrad or Grad. The results form a 2x2 contingency table."
- Data Matrix (matrix) = Input cell counts row by row into c()
- Dimensions (nrow/ncol) = Define 2 rows and 2 columns
How to use this snippet: Below is the bare-bones math logic for the problem above. When you solve your assignment, copy this snippet and change the inputs! No fancy `print()` commands are needed.
# Frequency table
tbl <- table(x)
prop.table(tbl)
# Hist / Boxplot
hist(x, breaks = "Sturges", main = "Histogram of x")
boxplot(x, horizontal = TRUE, main = "Boxplot of x")Storing Data (Vectors)
Use <- to store a list of values in a variable. The c() function combines values into a vector.
# Create a vector named 'scores'
scores <- c(88, 92, 95, 75, 85)
# Create a sequence from 1 to 100
numbers <- 1:100Generating Random Numbers
Create random samples or numbers from a uniform distribution.
# Select 10 random integers from 1 to 1000 (no repeats)
sample(1:1000, 10, replace = FALSE)
# Generate 5 random decimals between 0 and 1
runif(5)Measures of Center
Calculate the mean (average) and median (middle value) of a dataset.
Key formulas:
$$\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i$$
$$\text{Median: middle value after sorting the data}$$
grades <- c(95, 82, 78, 90, 88, 65)
mean(grades) # Output: 83
median(grades) # Output: 85Measures of Spread
Describe the variability or dispersion of data points.
Key formulas:
$$s^2 = \frac{\sum_{i=1}^{n} (x_i - \bar{x})^2}{n-1}, \qquad s = \sqrt{s^2}$$
$$\text{Range} = \max(x_i) - \min(x_i)$$
$$\text{IQR} = Q_3 - Q_1$$
grades <- c(95, 82, 78, 90, 88, 65)
sd(grades) # Sample Standard Deviation: 11.25...
var(grades) # Sample Variance: 126.8
range(grades) # Min and Max: 65 95
fivenum(grades) # Min, Q1, Median, Q3, MaxBoxplot
Visualize the five-number summary (min, Q1, median, Q3, max).
grades <- c(95, 82, 78, 90, 88, 65, 50, 98)
boxplot(grades)Chapter 4: Probability
Foundation Basic probability rules and counting.
Combinations & Permutations
Calculate the number of ways to choose or arrange items from a set.
$$\binom{n}{k} = \frac{n!}{k!(n-k)!}$$
# Combinations: How many ways to choose 3 from 10 (order doesn't matter)
choose(10, 3) # C(10,3) = 120
# Permutations: How many ways to arrange 3 from 10 (order matters)
# We multiply choose(n,k) by k!
choose(10, 3) * factorial(3) # P(10,3) = 720
Chapter 5: Discrete Random Variables
Distributions Expected Value, Binomial, and Poisson.
General Discrete RV
Key formulas:
$$E[X] = \sum x_i p_i$$
$$\sigma_X = \sqrt{\sum (x_i - \mu)^2 p_i}$$
Example Scenario: Expected Value
"A bakery tracks the number of specialty cakes ordered per day: 0, 1, 2,3. Historical records show the probabilitiesare respectively 10%, 30%, 40%, and 20%. Calculate the expected number of cakes ordered."
- Values Array (x_vals) = c(0, 1, 2, 3)
- Probabilities Array (p_vals) = c(0.10, 0.30, 0.40, 0.20)(Convert percentages to decimals!)
How to use this snippet: Below is the bare-bones math logic for the problem above. When you solve your assignment, copy this snippet and change the inputs! No fancy `print()` commands are needed.
outcomes <- c(0, 1, 2)
probabilities <- c(0.1, 0.3, 0.6)
# Expected Value E(X)
sum(outcomes * probabilities)
# Standard Deviation
mu <- sum(outcomes * probabilities)
sqrt(sum((outcomes - mu)^2 * probabilities))
Binomial Distribution
$$P(X=k) = \binom{n}{k} p^k (1-p)^{n-k}$$
# X ~ Bin(n=20, p=0.3)
n <- 20; p <- 0.3
# dbinom = "Density" (Probability of EXACT value)
dbinom(5, size=n, prob=p) # P(X = 5)
# pbinom = "Probability" (Cumulative <= value)
pbinom(5, size=n, prob=p) # P(X <= 5)
# P(8 <= X <= 12) = P(X<=12) - P(X<=7)
pbinom(12, size=n, prob=p) - pbinom(7, size=n, prob=p)
Poisson Distribution
$$P(X=k) = \frac{\lambda^k e^{-\lambda}}{k!}$$
# X ~ Poisson(lambda=4)
lam <- 4
# dpois = "Density" (Exact)
dpois(5, lambda=lam) # P(X = 5)
# ppois = "Probability" (Cumulative <=)
ppois(5, lambda=lam) # P(X <= 5)
Chapter 6: Normal Distribution
Distributions Normal probability calculations.
Normal Calculation Commands
Prefixes:p = Probability (Area to left), q = Quantile (Find z/x from Area).
$$Z = \frac{X - \mu}{\sigma}$$
Example Scenario: Extracting Normal Parameters
"The lifespans of a specific type of car tire are normally distributed with a mean of 40,000 miles and a standard deviation of 4,000 miles. What is the probability a tire lasts strictly more than 45,000 miles?"
- Population Mean (mu) = 40000
- Population SD (sigma) = 4000
- Target Value (cut-off) = 45000 (And because it says "more than", we use lower.tail=FALSE)
How to use this snippet: Below is the bare-bones math logic for the problem above. When you solve your assignment, copy this snippet and change the inputs! No fancy `print()` commands are needed.
# 1. Standard Normal Z ~ N(0, 1)
pnorm(1.96) # Area to LEFT of 1.96
pnorm(1.96, lower.tail=FALSE) # Area to RIGHT
qnorm(0.975) # Find Z score with 0.975 area to left
# 2. General Normal X ~ N(mu, sigma)
mu <- 70; sigma <- 10
# Find P(X < 84)
pnorm(84, mean=mu, sd=sigma)
# Find P(X > 84)
pnorm(84, mean=mu, sd=sigma, lower.tail=FALSE)
# Find X cutoff for top 10% (Area left = 0.90)
qnorm(0.90, mean=mu, sd=sigma)
Chapter 8: Confidence Intervals (One Sample)
Inference Estimating a single population mean.
Confidence Interval for Mean (σ Known)
Example Scenario: Extracting the Data
"A regional coffee chain wants to estimate the mean temperature of its served lattes across all locations. The espresso machine's documented engineering specifications guarantee that the standard deviation of brewing temperatures is strictly 2.5°F.A random sample of 35 lattes served today has an average temperature of 158°F. Construct a 95% confidence interval for the true mean temperature."
- Population SD ($\sigma$) = 2.5 (It says "guaranteed strict specs", so it's the known population parameter!)
- Sample Size ($n$) = 35
- Sample Mean ($\bar{x}$) = 158
- Confidence Level = 0.95 (So $\alpha$ = 1 - 0.95 = 0.05)
Formula: $$\bar{x} \pm z^* \left(\frac{\sigma}{\sqrt{n}}\right)$$
How to use this snippet: Below is the bare-bones math logic for the problem above. When you do your homework, copy this snippet and trim/change the numbers to fit your specific problem! No fancy `print()` commands are needed — R automatically prints the last line you run.
# 1. Input the extracted data
sigma <- 2.5
n <- 35
x_bar <- 158
conf_level <- 0.95
# 2. Math Calculations (do not change this structure!)
alpha <- 1 - conf_level
z_star <- qnorm(1 - alpha/2) # Finds the critical Z-value
ME <- z_star * (sigma / sqrt(n)) # Margin of Error
# 3. Final Boundaries
CI_lower <- x_bar - ME
CI_upper <- x_bar + ME
c(CI_lower, CI_upper) # This line prints the array to your console
Confidence Interval for Mean (σ Unknown)
Formula: $$\bar{x} \pm t^* \left(\frac{s}{\sqrt{n}}\right)$$
# --- METHOD A: Using Summary Statistics (Word Problems) ---
conf_level <- 0.95 # e.g., 0.95 for 95%, 0.99 for 99%
alpha <- 1 - conf_level # Automatically calculated
n <- ? # Sample Size
x_bar <- ? # Sample Mean
s <- ? # Sample Standard Deviation
# --- METHOD B: Using Raw Data (Uncomment if needed) ---
# data <- c(...)
# n <- length(data)
# x_bar <- mean(data)
# s <- sd(data)
# 1. Degrees of Freedom
df <- n - 1
# 2. Critical Value (t*)
t_star <- qt(1 - alpha/2, df)
# 3. Margin of Error (ME)
ME <- t_star * (s / sqrt(n))
# 4. Confidence Interval
c(x_bar - ME, x_bar + ME)
Shortcut using t.test (Only for Raw Data)
data <- c(...)
t.test(data, conf.level = 0.95)$conf.int
Finding Required Sample Size ($n$)
Formula: $$n = \left(\frac{z^* \cdot \sigma}{E}\right)^2$$
Reminder: Always round UP for sample size!
# 1. Given Parameters
E <- ? # Target Margin of Error
sigma <- ? # Estimated Population SD
conf_level <- 0.95 # Desired Confidence Level
alpha <- 1 - conf_level
# 2. Critical Value (z*)
z_star <- qnorm(1 - alpha/2)
# 3. Exact Sample Size Calculation
n_exact <- ((z_star * sigma) / E)^2
n_exact
# 4. Apply the Round-Up Rule
n_final <- ceiling(n_exact)
n_final
Chapter 9: Hypothesis Testing (One Sample)
Inference Tests for a single population mean.
One-sample Z-test (σ Known)
Test Statistic: $$z = \frac{\bar{x} - \mu_0}{\sigma / \sqrt{n}}$$
# --- METHOD A: Using Summary Statistics (Word Problems) ---
sigma <- ? # Known Pop SD
mu_0 <- ? # Null Hypothesis Mean claim
x_bar <- ? # Sample Mean
n <- ? # Sample Size
# --- METHOD B: Using Raw Data (Uncomment if needed) ---
# data <- c(...)
# x_bar <- mean(data)
# n <- length(data)
# 1. Z-Statistic
z <- (x_bar - mu_0) / (sigma / sqrt(n))
# 2. P-values
# Left-tailed (Ha: mu < mu0)
p_left <- pnorm(z)
# Right-tailed (Ha: mu > mu0)
p_right <- 1 - pnorm(z)
# Two-tailed (Ha: mu != mu0)
p_two <- 2 * (1 - pnorm(abs(z)))
# Output results
z
p_two # (or p_left/p_right depending on your Ha)
One-sample t-test (σ Unknown)
Test Statistic: $$t = \frac{\bar{x} - \mu_0}{s / \sqrt{n}}$$
Example Scenario: Extracting the Claim
"A city ordinance states that residential street speed limits should average 25 mph. A neighborhood committee clocks 12 randomly selected cars, finding an average speed of 28.5 mph with a standard deviation of 3.2 mph. Test if the true average speed is strictly greater than 25 mph."
- Hypothesized Mean (mu_0) = 25 (The baseline claim)
- Sample Size (n) = 12 (Degrees of freedom will be 11)
- Sample Mean (x_bar) = 28.5
- Sample SD (s) = 3.2 (Since population $\sigma$ is unknown, we use a t-test!)
How to use this snippet: Below is the bare-bones math logic for the problem above. When you solve your assignment, copy this snippet and change the inputs! No fancy `print()`commands are needed.
# --- METHOD A: Using Summary Statistics (Word Problems) ---
mu_0 <- ? # Null Hypothesis Mean claim
x_bar <- ? # Sample Mean
s <- ? # Sample Standard Deviation
n <- ? # Sample Size
# --- METHOD B: Using Raw Data (Uncomment if needed) ---
# data <- c(...)
# x_bar <- mean(data)
# s <- sd(data)
# n <- length(data)
# 1. t-Statistic and df
t <- (x_bar - mu_0) / (s / sqrt(n))
df <- n - 1
# 2. P-values (using pt instead of pnorm)
p_two <- 2 * (1 - pt(abs(t), df = df))
t; df; p_two
Shortcut using t.test (Only for Raw Data)
# Built-in one-sample t-test
# data <- c(...)
# t.test(data, mu = mu_0, alternative = "two.sided")
Chapter 10: Two-Sample Inference
Inference Comparing two population means (Independent & Paired).
Two-sample t-test (Pooled, $\sigma_1 = \sigma_2$)
Used for independent samples with assumed equal population variances.
Pooled Variance: $$S_p^2 = \frac{(n_1 - 1)s_1^2 + (n_2 - 1)s_2^2}{n_1 + n_2 - 2}$$
Test Statistic: $$t = \frac{(\bar{x}_1 - \bar{x}_2) - \Delta_0}{S_p\sqrt{\frac{1}{n_1} + \frac{1}{n_2}}}$$
Confidence Interval: $$(\bar{x}_1 - \bar{x}_2) \pm t^* \left( S_p\sqrt{\frac{1}{n_1} + \frac{1}{n_2}} \right)$$
# 1. Enter your two independent samples:
group1 <- c(10, 12, 11, 13, 12)
group2 <- c(9, 11, 10, 12, 11)
alpha <- 0.05 # Significance level
delta_0 <- 0 # null difference: mu1 - mu2
# 2. Basic summaries:
n1 <- length(group1)
n2 <- length(group2)
x_bar1 <- mean(group1)
x_bar2 <- mean(group2)
s1 <- sd(group1)
s2 <- sd(group2)
# 3. Pooled variance:
S_p2 <- (((n1 - 1) * s1^2) + ((n2 - 1) * s2^2)) / (n1 + n2 - 2)
SE <- sqrt(S_p2 * (1/n1 + 1/n2))
# 4. t-statistic and degrees of freedom:
t_stat <- ((x_bar1 - x_bar2) - delta_0) / SE
df <- n1 + n2 - 2
# 5. Two-tailed test (H_a: mu1 != mu2):
p_two <- 2 * (1 - pt(abs(t_stat), df = df))
critical_value_two_upper <- qt(1 - alpha/2, df = df)
critical_value_two_lower <- qt(alpha/2, df = df)
# 6. Left-tailed test (H_a: mu1 < mu2):
p_left <- pt(t_stat, df = df)
critical_value_left <- qt(alpha, df = df)
# 7. Right-tailed test (H_a: mu1 > mu2):
p_right <- 1 - pt(t_stat, df = df)
critical_value_right <- qt(1 - alpha, df = df)
# 8. Two-sided Confidence Interval for (mu1 - mu2):
CI_lower <- (x_bar1 - x_bar2) - critical_value_two_upper * SE
CI_upper <- (x_bar1 - x_bar2) + critical_value_two_upper * SE
# 8b. Left-sided Confidence Interval (for H_a: mu1 < mu2)
CI_left_lower <- -Inf
CI_left_upper <- (x_bar1 - x_bar2) + critical_value_right * SE
# 8c. Right-sided Confidence Interval (for H_a: mu1 > mu2)
CI_right_lower <- (x_bar1 - x_bar2) - critical_value_right * SE
CI_right_upper <- Inf
# 9. Values you usually report:
t_stat
S_p2
df
p_two
critical_value_two_lower
critical_value_two_upper
p_left
critical_value_left
p_right
critical_value_right
CI_lower
CI_upper
CI_left_lower
CI_left_upper
CI_right_lower
CI_right_upper
Use this when you compare two independent groups and are comfortable assuming equal population variances.
Two-sample t-test (Welch, $\sigma_1 \neq \sigma_2$)
Used for independent samples with unequal population variances (default in R).
Test Statistic: $$t = \frac{(\bar{x}_1 - \bar{x}_2) -\Delta_0}{\sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}}$$
Confidence Interval: $$(\bar{x}_1 - \bar{x}_2) \pm t^* \left(\sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}} \right)$$
Degrees of Freedom (Welch-Satterthwaite):
$$ df \approx \frac{\left( \frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}\right)^2}{\frac{(s_1^2/n_1)^2}{n_1-1} + \frac{(s_2^2/n_2)^2}{n_2-1}} $$
# 1. Enter your two independent samples:
group1 <- c(10, 12, 11, 13, 12)
group2 <- c(9, 11, 10, 12, 11)
alpha <- 0.05 # Significance level
delta_0 <- 0 # null difference: mu1 - mu2
# 2. Basic summaries:
n1 <- length(group1)
n2 <- length(group2)
x_bar1 <- mean(group1)
x_bar2 <- mean(group2)
s1 <- sd(group1)
s2 <- sd(group2)
# 3. t-statistic using separate variances:
SE <- sqrt(s1^2/n1 + s2^2/n2)
t_stat <- ((x_bar1 - x_bar2) - delta_0) / SE
# 4. Approximate degrees of freedom (Welch-Satterthwaite):
df_num <- SE^4
df_den <- ((s1^2/n1)^2)/(n1 - 1) + ((s2^2/n2)^2)/(n2 - 1)
df <- df_num / df_den
# 5. Two-tailed test (H_a: mu1 != mu2):
p_two <- 2 * (1 - pt(abs(t_stat), df = df))
critical_value_two_upper <- qt(1 - alpha/2, df = df)
critical_value_two_lower <- qt(alpha/2, df = df)
# 6. Left-tailed test (H_a: mu1 < mu2):
p_left <- pt(t_stat, df = df)
critical_value_left <- qt(alpha, df = df)
# 7. Right-tailed test (H_a: mu1 > mu2):
p_right <- 1 - pt(t_stat, df = df)
critical_value_right <- qt(1 - alpha, df = df)
# 8. Two-sided Confidence Interval for (mu1 - mu2):
CI_lower <- (x_bar1 - x_bar2) - critical_value_two_upper * SE
CI_upper <- (x_bar1 - x_bar2) + critical_value_two_upper * SE
# 8b. Left-sided Confidence Interval (for H_a: mu1 < mu2)
CI_left_lower <- -Inf
CI_left_upper <- (x_bar1 - x_bar2) + critical_value_right * SE
# 8c. Right-sided Confidence Interval (for H_a: mu1 > mu2)
CI_right_lower <- (x_bar1 - x_bar2) - critical_value_right * SE
CI_right_upper <- Inf
# 9. Values you usually report:
t_stat
df
p_two
critical_value_two_lower
critical_value_two_upper
p_left
critical_value_left
p_right
critical_value_right
CI_lower
CI_upper
CI_left_lower
CI_left_upper
CI_right_lower
CI_right_upper
Two-sample t-tests using t.test
# Welch two-sample t-test (unpooled, default)
t.test(group1, group2,
alternative = "two.sided",
var.equal = FALSE,
conf.level = 0.95)
# Pooled two-sample t-test (equal variances)
t.test(group1, group2,
alternative = "two.sided",
var.equal = TRUE,
conf.level = 0.95)
Math-Only Snippet: Effect size (Cohen's d)
$$d=\frac{\bar x_1-\bar x_2}{s_p},\qquad s_p=\sqrt{\frac{(n_1-1)s_1^2+(n_2-1)s_2^2}{n_1+n_2-2}}$$
# Math-only: Cohen's d (pooled SD)
sp2 <- (((n1 - 1)*s1^2) + ((n2 - 1)*s2^2)) / (n1 + n2 - 2)
sp <- sqrt(sp2)
d <- (x_bar1 - x_bar2) / sp
dMath-Only Snippet: Two-sample CI (manual, no functions)
Hand-compute a 95% CI for \((\mu_1-\mu_2)\) using Welch’s formula.
# Math-only: two-sample CI for (mu1 - mu2) (Welch, manual)
xbar1 <- mean(group1); s1 <- sd(group1); n1 <- length(group1)
xbar2 <- mean(group2); s2 <- sd(group2); n2 <- length(group2)
SE <- sqrt(s1^2/n1 + s2^2/n2)
df <- (s1^2/n1 + s2^2/n2)^2 / ((s1^2/n1)^2/(n1-1) + (s2^2/n2)^2/(n2-1))
tstar <- qt(0.975, df)
CI <- (xbar1 - xbar2) + c(-1,1)*tstar*SE
CIPaired t-test
Used when samples are paired (e.g., before/after, matched subjects).
Test Statistic (on differences $d$): $$t = \frac{\bar{d} - \mu_d}{s_d / \sqrt{n}}$$
Confidence Interval: $$\bar{d} \pm t^* \left(\frac{s_d}{\sqrt{n}}\right)$$
# Paired data (e.g., before and after intervention):
before <- c(200, 195, 210, 205, 198)
after <- c(190, 185, 205, 200, 192)
alpha <- 0.05 # Significance level
# Calculate the differences:
diff <- before - after
# Summary statistics for differences:
mean_diff <- mean(diff)
s_diff <- sd(diff)
n <- length(diff)
# Compute the t-statistic:
t <- mean_diff / (s_diff / sqrt(n))
# Degrees of freedom:
df <- n - 1
# Two-tailed test:
p_two <- 2 * (1 - pt(abs(t), df = df))
critical_value_two_upper <- qt(1 - alpha/2, df = df)
critical_value_two_lower <- qt(alpha/2, df = df)
# Left-tailed test:
p_left <- pt(t, df = df)
critical_value_left <- qt(alpha, df = df)
# Right-tailed test:
p_right <- 1 - pt(t, df = df)
critical_value_right <- qt(1 - alpha, df = df)
# Compute Confidence Interval (Two-tailed):
CI_lower <- mean_diff - critical_value_two_upper * (s_diff/sqrt(n))
CI_upper <- mean_diff + critical_value_two_upper * (s_diff/sqrt(n))
# Output the t-statistic, mean difference, standard deviation of differences,
# degrees of freedom, p-values, and Confidence Interval:
t
mean_diff
s_diff
df
p_two
critical_value_two_lower
critical_value_two_upper
p_left
critical_value_left
p_right
critical_value_right
CI_lower
CI_upperPaired t-test using t.test
# Paired t-test with built-in function
t.test(before, after,
paired = TRUE,
alternative = "two.sided",
conf.level = 0.95)
Mann-Whitney U Test (Independent)
Non-parametric alternative to the independent two-sample t-test. Tests for differences in medians or distributions.
# Mann-Whitney U Test (Independent Samples)
# Also known as Wilcoxon Rank-Sum test
group1 <- c(10, 12, 11, 13, 12, 15)
group2 <- c(9, 11, 10, 12, 11)
# R's wilcox.test performs this test for independent samples
# 'exact = FALSE' uses a normal approximation for the p-value
# 'correct = TRUE' applies a continuity correction
test_result <- wilcox.test(group1, group2,
paired = FALSE,
exact = FALSE,
correct = TRUE)
test_result # R prints the test output automatically
test_result$p.value # p-value
Wilcoxon Signed-Rank Test (Paired)
Non-parametric alternative to the paired t-test. Tests for differences in paired observations.
# Wilcoxon Signed-Rank Test (Paired Samples)
before <- c(200, 195, 210, 205, 198)
after <- c(190, 185, 205, 200, 192)
# R's wilcox.test with paired = TRUE performs the signed-rank test
test_result <- wilcox.test(before, after,
paired = TRUE,
exact = FALSE,
correct = TRUE)
test_result # R prints the test output automatically
test_result$p.value # p-value
Chapter 12: Population Proportions
Inference Tests and CIs for proportions (One & Two Sample).
One-sample z-test for Proportion
Test Statistic: $$z = \frac{\hat{p} - p_0}{\sqrt{\frac{p_0(1-p_0)}{n}}}$$
# One-sample z-test for Proportion
x <- 48; n <- 120; p0 <- 0.4
phat <- x/n
alpha <- 0.05
# Test statistic
z <- (phat - p0) / sqrt(p0*(1-p0)/n)
# P-values
p_left <- pnorm(z)
p_right <- 1 - pnorm(z)
p_two <- 2 * (1 - pnorm(abs(z)))
# Output
phat
z
p_two
p_left
p_right
Confidence Interval for Proportion
Confidence Interval (Wald): $$\hat{p} \pm z^* \sqrt{\frac{\hat{p}(1-\hat{p})}{n}}$$
x <- 48; n <- 120; phat <- x/n; alpha <- .05
z_star <- qnorm(1 - alpha/2)
ME <- z_star * sqrt(phat*(1-phat)/n)
CI_lower <- phat - ME
CI_upper <- phat + ME
# Output CI
CI_lower
CI_upper
Note: The Wald CI above can be unstable for small n or when \( \hat p \) is near 0 or 1. Prefer prop.test (Wilson score) or the plus-four(Agresti–Coull) interval in those cases.
Math-Only Snippet: Plus-Four (Agresti–Coull) CI for One Proportion
Formula: $$\tilde p = \dfrac{x+2}{n+4},\qquad \text{CI} = \tilde p \pm z^*\sqrt{\dfrac{\tilde p(1-\tilde p)}{n+4}}$$
Example Scenario: Plus-Four Interval
"Given $x=46$ successes and $n=50$ trials, use the one-proportion plus-four z-interval procedure to find the $90\%$ confidence interval."
- Successes (x) = 46
- Trials (n) = 50
- Alpha (1 - Conf) = 0.10
How to use this snippet: Below is the bare-bones math logic for the problem above. When you solve your assignment, copy this snippet and change the inputs! No fancy `print()`commands are needed.
# Plus-Four (Agresti–Coull) CI for one proportion (no custom functions)
x <- 46; n <- 50; alpha <- 0.10
x_tilde <- x + 2
n_tilde <- n + 4
p_tilde <- x_tilde / n_tilde
z <- qnorm(1 - alpha/2)
se <- sqrt(p_tilde * (1 - p_tilde) / n_tilde)
c(p_tilde - z*se, p_tilde + z*se)
Proportion test using prop.test
# One-sample proportion test
prop.test(x = 48, n = 120,
p = 0.40,
alternative = "two.sided",
conf.level = 0.95,
correct = FALSE)
Two-sample z-test for Proportion
Pooled Proportion (for Test Statistic): $$\hat{p}_{pool} = \frac{x_1 + x_2}{n_1 +n_2}$$
Test Statistic: $$z = \frac{(\hat{p}_1 -\hat{p}_2)}{\sqrt{\hat{p}_{pool}(1-\hat{p}_{pool})\left(\frac{1}{n_1} + \frac{1}{n_2}\right)}}$$
Confidence Interval (Unpooled SE): $$(\hat{p}_1 - \hat{p}_2) \pm z^*\sqrt{\frac{\hat{p}_1(1-\hat{p}_1)}{n_1} + \frac{\hat{p}_2(1-\hat{p}_2)}{n_2}}$$
# Two-sample z-test for Proportion
x1 <- 56; n1 <- 150
x2 <- 72; n2 <- 160
alpha <- 0.05
# Sample proportions
phat1 <- x1/n1
phat2 <- x2/n2
# Pooled proportion (for test statistic)
phat_pool <- (x1 + x2) / (n1 + n2)
# Test statistic
z <- (phat1 - phat2) / sqrt(phat_pool*(1-phat_pool)*(1/n1 + 1/n2))
# P-values
p_left <- pnorm(z)
p_right <- 1 - pnorm(z)
p_two <- 2 * (1 - pnorm(abs(z)))
# Confidence Interval (Unpooled standard error)
z_star <- qnorm(1 - alpha/2)
SE_unpooled <- sqrt(phat1*(1-phat1)/n1 + phat2*(1-phat2)/n2)
ME <- z_star * SE_unpooled
CI_lower <- (phat1 - phat2) - ME
CI_upper <- (phat1 - phat2) + ME
# Output
phat1; phat2
z
p_two
p_left
p_right
CI_lower
CI_upperProportion test using prop.test
# Two-sample proportion test
x <- c(56, 72)
n <- c(150, 160)
prop.test(x = x, n = n,
alternative = "two.sided",
conf.level = 0.95,
correct = FALSE)
Sample Size Calculation for a Target Margin of Error
If a target Margin of Error ($E$) is required, you can calculate the exact sample size($n$) backwards. You must always round UP to the nearest integer.
Scenario A: With an Educated Guess ($\hat{p}_g$)
$$n = \hat{p}_g (1 - \hat{p}_g) \left(\frac{z_{\alpha/2}}{E}\right)^2$$
# Sample size WITH an educated guess
E <- 0.04 # Target margin of error
p_guess <- 0.40 # Educated guess for proportion
alpha <- 0.05 # For a 95% Confidence Level
z_star <- qnorm(1 - alpha/2)
n <- p_guess * (1 - p_guess) * (z_star / E)^2
# Always round UP using ceiling()
n_required <- ceiling(n)
n_required
Scenario B: Without an Educated Guess (Worst-Case)
When no prior data exists, we assume $\hat{p}_g = 0.5$ because it maximizes the required sample size, playing it statistically safe.
$$n = 0.25 \left(\frac{z_{\alpha/2}}{E}\right)^2$$
# Sample size WITHOUT an educated guess (Uses p = 0.5)
E <- 0.03 # Target margin of error
alpha <- 0.01 # For a 99% Confidence Level
z_star <- qnorm(1 - alpha/2)
n <- 0.25 * (z_star / E)^2
# Always round UP using ceiling()
n_required <- ceiling(n)
n_required
Chapter 13: Chi-Square Procedures
Inference Tests for categorical data (Goodness of Fit & Association).
Chi-square tests and contingency tables
Key formulas (contingency)
$$E_{ij}=\frac{(\text{row }i\ \text{total})(\text{col }j\ \text{total})}{N}$$
$$X^2=\sum_{i=1}^r\sum_{j=1}^c \frac{(O_{ij}-E_{ij})^2}{E_{ij}},\qquad \text{df}=(r-1)(c-1)$$
GOF vs. Contingency — choose the right call: For goodness-of-fit (1 categorical variable with k categories), pass a vector of counts and a probability vector p. df = k − 1 (minus any parameters estimated). If you build a matrix by accident, R treats it as a contingency table and df becomes (r−1)(c−1).
# Goodness-of-fit (k = 5 ⇒ df = 4)
counts <- c(12, 3, 6, 20, 9) # observed
probs <- c(0.2, 0.1, 0.1, 0.3, 0.3) # stated distribution (sums to 1)
chisq.test(counts, p = probs, correct = FALSE)
# If any expected count < 5, prefer a simulated p-value:
chisq.test(counts, p = probs, simulate.p.value = TRUE, B = 10000)
If you see df = 8 or the warning “Chi-squared approximation may be incorrect,” you likely used a contingency-table call or at least one expected count was < 5.Combine sparse categories or use simulate.p.value = TRUE.
Making a table with matrix()
# Make a 2 x 3 contingency table from a list of counts
x <- c(12, 8, 5,
15, 9, 14)
M <- matrix(x,
nrow = 2,
ncol = 3,
byrow = TRUE)
M # Goodness-of-fit test
counts <- c(50, 30, 20)
probs <- c(0.5, 0.3, 0.2)
chisq.test(counts, p = probs, correct = FALSE)
# Test of association / homogeneity from a contingency table
M <- matrix(c(12, 8,
5, 15),
nrow = 2, byrow = TRUE)
chisq.test(M, correct = FALSE)
# Expected counts
chisq.test(M, correct = FALSE)$expected
# Row and column sums
rowSums(M)
colSums(M)
# Conditional row and column distributions
prop.table(M, margin = 1) # row marginals
prop.table(M, margin = 2) # column marginals
# Chi-square critical value (95% area to the left)
qchisq(0.95, df = 3)
# Chi-square critical value (5% area to the right)
qchisq(0.05, df = 3, lower.tail = FALSE)
GOF quick checklist (no branching)
Use vectors for GOF (one variable with k categories). df should be k − 1. Do not build a matrix for GOF.
# GOF quick checklist (no branching)
counts <- c(12, 3, 6, 20, 9)
probs <- c(0.2, 0.1, 0.1, 0.3, 0.3)
probs <- probs / sum(probs)
n <- sum(counts)
expected <- n * probs
expected
length(counts) - 1
min(expected)
chisq.test(counts, p = probs, correct = FALSE)
chisq.test(counts, p = probs, simulate.p.value = TRUE, B = 10000)
Math-Only Snippet: Chi-square from scratch (expected counts, X², p)
Build the expected table and compute \(X^2\) and the p-value directly.
# Math-only: chi-square from scratch (contingency table)
# M is an r x c matrix of counts
E <- outer(rowSums(M), colSums(M)) / sum(M)
X2 <- sum( (M - E)^2 / E )
df <- (nrow(M)-1)*(ncol(M)-1)
p <- 1 - pchisq(X2, df)
X2; df; pChapter 16: Analysis of Variance (ANOVA)
Inference Comparing multiple means.
F-distribution and one-way ANOVA
Key formulas (one-way ANOVA)
$$\text{SSB}=\sum_{j=1}^{k} n_j(\bar x_j-\bar x_G)^2,\quad\text{SSW}=\sum_{j=1}^{k}\sum_{i=1}^{n_j}(x_{ij}-\bar x_j)^2,\quad \text{SST}=\text{SSB}+\text{SSW}$$
$$\text{MSB}=\frac{\text{SSB}}{k-1},\qquad \text{MSW}=\frac{\text{SSW}}{N-k},\qquad F=\frac{\text{MSB}}{\text{MSW}}$$
$$\eta^2=\frac{\text{SSB}}{\text{SST}} \text{ (effect size)}$$
Example Scenario: Comparing Multiple Means
"Testing if there is a significant difference in weight loss among three diets: Low-Carb, Mediterranean,and Vegan. We have the individual weight loss figures for 5 people on each diet."
- Group 1 Array (g1) = c(5.2, 4.8, 4.3, 5.0, 4.7)
- Group 2 Array (g2) = c(3.1, 2.9, 3.4, 3.2, 3.0)
- Group 3 Array (g3) = c(4.1, 4.4, 3.9, 4.2, 4.0)
How to use this snippet: Below is the bare-bones math logic for the problem above. When you solve your assignment, copy this snippet and change the inputs! No fancy `print()` commands are needed.
# Effect size from summary parts already computed in this panel:
SST <- SSB + SSW
eta2 <- SSB / SST
eta2 # F-distribution
df1 <- 2; df2 <- 15
qf(0.95, df1 = df1, df2 = df2) # value with 95% area to the left
pf(3.2, df1 = df1, df2 = df2) # P(F <= 3.2)
# Example one-way ANOVA setup
Group <- rep(c("A", "B", "C"), times = c(5, 5, 5))
X <- c(12, 15, 14, 13, 16,
10, 11, 9, 12, 10,
18, 17, 16, 19, 18)
fit <- aov(X ~ Group)
anova(fit)
One-way ANOVA from Summary Statistics (no aov)
Compute the ANOVA F statistic directly from group sizes, means, and standard deviations without calling aov().
# One-way ANOVA from summary statistics (no aov)
n <- c(12, 10, 8) # group sizes
xbar <- c(18.2, 20.1, 22.0) # group means
s <- c(3.5, 4.1, 3.8) # group standard deviations
N <- sum(n)
gbar <- sum(n * xbar) / N
SSB <- sum( n * (xbar - gbar)^2 )
SSW <- sum( (n - 1) * s^2 )
df1 <- length(n) - 1
df2 <- N - length(n)
MSB <- SSB / df1
MSW <- SSW / df2
F <- MSB / MSW
pval <- 1 - pf(F, df1, df2)
F; df1; df2; pvalMath-Only Snippet: From Raw Data to (n, x̄, s) by Group
Compute the inputs (sizes, means, sds) directly from raw vectors to feed into the summary-stats ANOVA above.
# Math-only: from raw data to (n, xbar, s) by group
# x: numeric response, g: group labels (factor or character)
n <- as.numeric(table(g))
xbar <- tapply(x, g, mean)
s <- tapply(x, g, sd)Using rep() to build group labels
# Repeating labels for groups (useful for ANOVA)
Group <- rep(c("A", "B", "C"),
times = c(5, 5, 5))
Group
Troubleshooting Common R Errors
Help! "What went wrong?" - How to read and fix red errors instead of panicking.
Error 1: object 'x' not found
- What it means: R has no idea what 'x' is.
- How to fix:
- Did you actually run the line of code that creates `x` first? (e.g., `x <- 5`)
- Is it spelled exactly the same? R is case-sensitive! (`Data` is not the same as `data`).
Error 2: unexpected symbol in "..."
- What it means: There is a typo confusing the system.
- How to fix: Check that specific line for missing commas, forgotten closing parentheses
), or unclosed quotation marks" ".
Error 3: could not find function "..."
- What it means: R doesn't recognize the command you typed.
- How to fix:
- Did you forget to load the package? (e.g., you need to run
library(fastR2)before using its functions). - Did you capitalize a built-in function by mistake? (It must be
mean(), notMean()).
- Did you forget to load the package? (e.g., you need to run
Error 4: + sign stuck in the Console
- What it means: R is waiting for you to finish your thought because you missed a closing parenthesis
)on a previous line. - How to fix: Click into the Console and press the ESC key on your keyboard to cancel and try running the code again.
Reference Tables
Tables Common critical values for the distributions used in this course.
Standard Normal (Z) Critical Values
Most problems in this class only need a few standard cutoffs. You can still use the full Z-table from your notes or textbook.
| Tail / CI | Area | Critical z | R command |
|---|---|---|---|
| Left tail | 0.05 | −1.645 | qnorm(0.05) |
| Right tail | 0.05 | 1.645 | qnorm(0.95) |
| Two-sided CI | 95% | ±1.96 | qnorm(0.975) |
| Two-sided CI | 99% | ±2.576 | qnorm(0.995) |
Student's t Critical Values
We usually use R to get the exact t critical value for a given confidence level and degrees of freedom.
| df | 95% CI (two-sided) | 99% CI (two-sided) | R command (upper tail) |
|---|---|---|---|
| 10 | ±2.228 | ±3.169 | qt(0.975, df = 10) |
| 20 | ±2.086 | ±2.845 | qt(0.975, df = 20) |
| 30 | ±2.042 | ±2.750 | qt(0.975, df = 30) |
General pattern: upper-tail cutoff is qt(1 - \alpha/2, df) for a two-sided CI with level 1 - \alpha.
Chi-square Critical Values
Used in goodness-of-fit and association tests. Here are a few common right-tail cutoffs.
| df | Right-tail 0.05 | Right-tail 0.01 | R command |
|---|---|---|---|
| 1 | 3.84 | 6.63 | qchisq(0.95, df = 1) |
| 2 | 5.99 | 9.21 | qchisq(0.95, df = 2) |
| 3 | 7.81 | 11.34 | qchisq(0.95, df = 3) |
General pattern: right-tail cutoff is qchisq(1 - \alpha, df).
F Critical Values
Used for ANOVA. You will normally use R to get these, but here are some typical cutoffs.
| df1 (numerator) | df2 (denominator) | Right-tail 0.05 | R command |
|---|---|---|---|
| 2 | 10 | 4.10 | qf(0.95, df1 = 2, df2 = 10) |
| 2 | 20 | 3.49 | qf(0.95, df1 = 2, df2 = 20) |
| 3 | 20 | 3.10 | qf(0.95, df1 = 3, df2 = 20) |
General pattern: right-tail cutoff is qf(1 - \alpha, df1, df2).
Chapter 7: Sampling Distributions
Concepts Sampling distribution of $\bar X$ and the CLT.
# CLT simulation
set.seed(1)
mu <- 70; sigma <- 10; n <- 30
B <- 5000
xbar <- replicate(B, mean(rnorm(n, mu, sigma)))
hist(xbar, breaks=30, main="Sampling dist. of x̄")
mean(xbar); sd(xbar) # ≈ mu, sigma/sqrt(n)Use this to see how sample means behave across many repeated samples and to visualize the Central Limit Theorem. You do not need to memorize this code; it is here to help you see where the formulas for the sampling distribution come from.
All possible sample means using combinations
# Small example to see all possible sample means from combinations
x <- c(1, 2, 3, 4)
combn(x, 2) # all pairs of elements from x (without replacement)
combn(x, 2, mean) # the mean of each pair
# You can change 2 to any k with 1 < k < length(x).
Chapter 14: Regression & Correlation
Modeling Simple Linear Regression.
Simple Linear Regression
Model: $$ y = \beta_0 + \beta_1 x + \epsilon $$
Key formulas (simple linear regression)
$$b_1=\frac{\sum(x_i-\bar x)(y_i-\bar y)}{\sum(x_i-\bar x)^2},\qquad b_0=\bar y-b_1\bar x$$
$$\hat\sigma^2=\frac{\sum(y_i-\hat y_i)^2}{n-2},\qquad\mathrm{SE}(b_1)=\sqrt{\frac{\hat\sigma^2}{\sum(x_i-\bar x)^2}}$$
$$t=\frac{b_1}{\mathrm{SE}(b_1)},\quad \text{CI}_{b_1}: \ b_1 \pm t^*\,\mathrm{SE}(b_1)$$
Example Scenario: The Central Limit Theorem
"A factory produces lightbulbs with a known population standard deviation of 120 hours. If an inspector takes a random sample of 50 bulbs, what is the standard errorof the sample mean?"
- Population SD (sigma) = 120
- Sample Size (n) = 50 (Ensure $n \ge 30$ for CLT)
How to use this snippet: Below is the bare-bones math logic for the problem above. When you solve your assignment, copy this snippet and change the inputs! No fancy `print()` commands are needed.
x_data <- c(10, 15, 20, 25, 30)
y_data <- c(12, 18, 22, 28, 35)
model <- lm(y_data ~ x_data)
summary(model)
coef(model)Scatterplots and data frames
# Create a data frame
df <- data.frame(x = x_data, y = y_data)
# Basic scatterplot
plot(x_data, y_data)
# Scatterplot with some options
plot(x_data, y_data,
cex = 1.3, # point size
pch = 16, # filled circles
col = "blue4") # point color
# Correlation coefficient
cor(x_data, y_data)
# Add regression line after plot
b0 <- coef(model)[1]
b1 <- coef(model)[2]
abline(b0, b1)
95% Confidence Intervals for Coefficients
Use confint() on your fitted object. If you named it model as above:
# 95% CIs for regression coefficients (intercept and slope)
confint(model, level = 0.95)
# If your object is named 'fit':
# confint(fit, level = 0.95)
# Example for 90%: confint(model, level = 0.90)Math-Only Snippet: CI for mean response at x₀ (no predict)
Compute a CI for the mean response at a specific x-value using formulas only(no predict()).
$${\\mathrm{SE}_{\\bar y}(x_0)=\\sqrt{\\hat\\sigma^2\\left(\\frac1n+\\frac{(x_0-\\bar x)^2}{S_{xx}}\\right)}\\,,\\quad S_{xx}=\\sum(x_i-\\bar x)^2}$$
# Math-only: CI for mean response at x0 (no predict)
x0 <- 25
xbar <- mean(x_data); ybar <- mean(y_data)
Sxx <- sum( (x_data - xbar)^2 )
Sxy <- sum( (x_data - xbar)*(y_data - ybar) )
b1 <- Sxy / Sxx
b0 <- ybar - b1*xbar
# residual variance
e2 <- sum( (y_data - (b0 + b1*x_data))^2 )
sig2 <- e2 / (length(x_data)-2)
# SE and 95% CI
se_mean <- sqrt( sig2 * ( 1/length(x_data) + (x0 - xbar)^2 / Sxx ) )
tstar <- qt(0.975, df = length(x_data)-2)
yhat0 <- b0 + b1*x0
c(yhat0 - tstar*se_mean, yhat0 + tstar*se_mean)Math-Only Snippet: Prediction interval for a new y at x₀ (no predict)
Interval for a new observation adds model noise to the mean-response SE.
$${\\mathrm{SE}_{\\text{pred}}(x_0)=\\sqrt{\\hat\\sigma^2\\left(1+\\frac1n+\\frac{(x_0-\\bar x)^2}{S_{xx}}\\right)}\\,,\\quad \\hat y_0 \\pm t^*\\,\\mathrm{SE}_{\\text{pred}}(x_0)}$$
# Math-only: prediction interval at x0 (no predict)
se_pred <- sqrt( sig2 * ( 1 + 1/length(x_data) + (x0 - xbar)^2 / Sxx ) )
c(yhat0 - tstar*se_pred, yhat0 + tstar*se_pred)Math-Only Snippet: Manual Formulas (no predict)
If you want step-by-step calculations for homework, this derives slope/intercept and the slope CI from formulas (no automation):
# Math-only: manual OLS formulas (no predict)
xbar <- mean(x_data); ybar <- mean(y_data)
Sxx <- sum( (x_data - xbar)^2 )
Sxy <- sum( (x_data - xbar)*(y_data - ybar) )
b1 <- Sxy / Sxx
b0 <- ybar - b1*xbar
# residual variance and SE(b1)
e2 <- sum( (y_data - (b0 + b1*x_data))^2 )
sig2 <- e2 / (length(x_data)-2)
se_b1 <- sqrt(sig2 / Sxx)
# t and CI for slope (95%)
tval <- b1 / se_b1
tstar <- qt(0.975, df = length(x_data)-2)
c(b1 - tstar*se_b1, b1 + tstar*se_b1)