BIOL 235 Biostatistics Study Guide Chapters 11-12

Introduction to ANOVA in R (Lecture 28)

  • Core Concepts of ANOVA:

    • ANOVA stands for Analysis of Variance.

    • It is used to compare the means of three or more independent groups simultaneously to avoid inflating the Type I error rate that occurs with multiple t-tests.

    • For example, with 10 groups, there would be 45 pairwise t-tests; ANOVA collapses this into a single global test.

  • Hypotheses for ANOVA:

    • Null Hypothesis (H0H_0): μ1=μ2=⋯=μI\mu_1 = \mu_2 = \dots = \mu_I (all population means are equal).

    • Alternative Hypothesis (HaH_a): At least one μi\mu_i differs from at least one other μj\mu_j.

  • Key R Functions for Fitting Models:

    • fit <- aov(y ~ group, data = df): Fits a basic one-way ANOVA model.

    • summary(fit): Prints the ANOVA table containing degrees of freedom (df), Sum of Squares (SS), Mean Squares (MS), F-statistic (F value), and p-value (Pr(>F)Pr(>F)).

  • Data Preparation (Stacking):

    • The aov() function requires data in "long" format (one column for numeric values, one for group labels).

    • Wide format data (individual columns per group) must be converted using the stack() function.

    • Syntax example: stacked <- stack(list(groupA = dfgroupA,groupB=dfgroupA, groupB = dfgroupB, groupC = dfgroupC))</code>.</p></li><li><p>Structureofstackeddata:</p><ul><li><p><code>stackedgroupC))</code>.</p></li><li><p>Structure of stacked data:</p><ul><li><p><code>stackedvalues: Contains all numeric observations.

    • stackedind</code>:Containsthefactorlabelsforeachgroup.</p></li></ul></li><li><p>Pre−analysischeck:Alwaysuse<code>head(stacked)</code>toconfirmformattingbeforerunningthemodel.</p></li></ul></li><li><p><strong>CornDatasetExample:</strong></p><ul><li><p>Code:<code>corn<−read.table(′corn.txt′,header=TRUE)</code></p></li><li><p><code>stacked<−stack(list(ne=cornind</code>: Contains the factor labels for each group.</p></li></ul></li><li><p>Pre-analysis check: Always use <code>head(stacked)</code> to confirm formatting before running the model.</p></li></ul></li><li><p><strong>Corn Dataset Example:</strong></p><ul><li><p>Code: <code>corn <- read.table('corn.txt', header = TRUE)</code></p></li><li><p><code>stacked <- stack(list(ne=cornne, wa=cornwa,nw=cornwa, nw=cornnw, ba=cornba,co=cornba, co=cornco))

    • fit <- aov(values ~ ind, data = stacked)

    • summary(fit)

    • Note: The left side of the ~ is the numeric response; the right side is the categorical grouping variable.

MS(between), MS(within), and the F Statistic (Lecture 29)

  • Reading the ANOVA Table Output:

    • Df (Degrees of Freedom):

      • Treatment (Between groups): I−1I - 1

      • Residuals (Within groups): n.−In. - I

      • Total: n.−1n. - 1 (where n.n. is total sample size and II is number of groups).

    • Sum Sq (Sum of Squares - SS):

      • Sum Squares Between: ∑ni(yˉi−yˉˉ)2\sum n_i(\bar{y}_i - \bar{\bar{y}})^2

      • Sum Squares Within: ∑(ni−1)si2\sum (n_i - 1)s_i^2

      • SStotal=SSbetween+SSwithinSS_{total} = SS_{between} + SS_{within}.

    • Mean Sq (Mean Square - MS): Calculated as SS/dfSS / df.

    • F value: The F-statistic is the ratio of Signal to Noise.

      • F=MSbetweenMSwithinF = \frac{MS_{between}}{MS_{within}}

    • Pr(>F): The p-value. Reject H0H_0 if p<0.05p < 0.05.

  • Signal-to-Noise Framework:

    • MS(between): Measures the spread of group means from the grand mean (The SIGNAL). how far spread out are the means

    • MS(within): Measures the spread of individuals within groups, also known as pooled variance (The NOISE). Measures how far apart individual data points are from each other.

    • F-statistic Interpetation:

      • F≈1F \approx 1: No evidence groups differ significantly

      • F≫1F \gg 1: Strong evidence at least one group mean differs significantly

Checking Assumptions and Two-Way ANOVA (Lecture 30)

  • Assumptions of ANOVA:

    1. Independent Random Samples: Determined by study design; cannot be tested statistically.

    2. Normality of Residuals: Checked using plot(fit) to view the Normal Q-Q plot. Points should follow the diagonal line.

    3. Equal Variances (Homoscedasticity): Checked using the Residuals vs Fitted plot. Look for an even spread around zero with no "fan" or "cone" shape.

  • Two-Way ANOVA Syntax:

    • aov(y ~ A + B, data = df): Main effects only (no interaction term).

    • aov(y ~ A * B, data = df): Includes main effects AND the interaction term (A:BA:B).

  • Workflow for Two-Way ANOVA:

    • Step 1: Fit the model with the interaction term (*).

    • Step 2: Check if the interaction is significant. If YES, stop and report it.

    • Step 3: If the interaction is NOT significant, re-fit the model using only main effects (+) and report those results.

  • Interaction Plots:

    • Parallel Lines: Indicate no interaction between variables.

    • Crossing/Diverging Lines: Indicate a significant interaction is present.

Linear Regression and Correlation in R (Lecture 31)

  • Usage Criteria: Used when both the predictor (XX) and the response (YY) are numeric variables.

  • Core Functions:

    • plot(x, y): Generates a scatterplot. Essential first step.

    • cor(x, y): Returns the correlation coefficient (rr).

    • cor.test(x, y): Full correlation test including rr, t-statistic, p-value, and 95% Confidence Interval for rr. This is the preferred function for formal testing.

    • fit <- lm(y ~ x, data = df): Fits the least-squares regression line.

    • summary(fit): Provides coefficients (b0,b1b_0, b_1), Standard Error, t-values, p-values, r2r^2, and ses_e.

    • abline(fit): Adds the regression line to the scatterplot.

    • influence.measures(fit): Flags points that shift the model drastically.

    • predict(fit, newdata=data.frame(x=val)): Evaluates the model at a specific XX value.

  • Mathematical Components of the Regression Line:

    • Equation: y^=b0+b1x\hat{y} = b_0 + b_1x

    • Slope (b1b_1): b1=r×(sYsX)b_1 = r \times (\frac{s_Y}{s_X}). Represents the average change in YY for a 1-unit increase in XX.

    • Intercept (b0b_0): b0=yˉ−b1xˉb_0 = \bar{y} - b_1\bar{x}.

    • The line always passes through the point (xˉ,yˉ)(\bar{x}, \bar{y}).

    • Residual Standard Error (ses_e): Typical vertical distance from points to the line (se=SSresidn−2\text{s}_e = \sqrt{\frac{SS_{resid}}{n-2}}).

    • Coefficient of Determination (r2r^2): The fraction of variance in YY explained by XX.

  • Correlation Coefficient (rr):

    • Measures strength and direction of the linear relationship.

    • Ranges from −1-1 to 11.

    • r=0r = 0 does not mean no relationship; it means no linear relationship.

Linear Regression Inference and Diagnostics (Lecture 32)

  • Standard Error of the Slope (SE(b1)SE(b_1)):

    • Formula: SE(b1)=sesxn−1SE(b_1) = \frac{s_e}{s_x \sqrt{n-1}}

    • Logic: Larger spread in XX (sxs_x) leads to smaller SE(b1)SE(b_1) and better precision. Larger residual noise (ses_e) leads to larger SE(b1)SE(b_1) and less precision.

  • Inference on β1\beta_1:

    • H0:β1=0H_0: \beta_1 = 0 (no linear relationship).

    • Ha:β1≠0H_a: \beta_1 \neq 0 (linear relationship exists).

    • t-statistic for slope: t=b1SE(b1)=rn−21−r2t = \frac{b_1}{SE(b_1)} = r \sqrt{\frac{n-2}{1-r^2}}.

    • Degrees of Freedom: n−2n - 2.

    • 95% CI for β1\beta_1: b1±t0.025×SE(b1)b_1 \pm t_{0.025} \times SE(b_1).

  • Interpretation of Residual Plots:

    • Starry Sky (Random Scatter): Model is appropriate.

    • U-shape/Arch: Indicates non-linearity (curvilinearity).

    • Fan/Cone Shape: Indicates heteroscedasticity (violated equal variance).

  • Outliers and Influence:

    • Low leverage: Points near xˉ\bar{x} but off the trend. Primarily shift the intercept.

    • High leverage: Points extreme in XX space.

    • Influential: Points that significantly change the slope and rr. Check with influence.measures() and look for an asterisk (*) in the inf column or points crossing Cook's distance lines at 0.5 or 1.

  • Data Scaling and Transformation:

    • Interpolation: Predicting within the observed range (reliable).

    • Extrapolation: Predicting outside the observed range (error-prone; avoid).

    • Exponential Trends: Apply log(y) transformation to achieve linearity for regression fitting.

Final Review and Decision Framework (Lecture 33)

  • Sutter's Four-Step Process:

    1. Define the question.

    2. Know your data (variable counts, types, paired/unpaired).

    3. LOOK AT THE DATA (graphs first).

    4. Use the right tool.

  • Master Test Choice Guide:

    • Numeric vs None (1 group): Mean + CI using t-distribution.

    • Numeric vs Categorical (2 groups, independent): t-test or Wilcoxon.

    • Numeric vs Categorical (2 groups, paired): Paired t-test.

    • Numeric vs Categorical (3+ groups): One-way ANOVA.

    • Numeric vs 2 Categorical variables: Two-way ANOVA.

    • Numeric vs Numeric (Linear): cor.test() and lm().

    • Categorical (1 var): Wilson CI (septilde()).

    • Categorical vs Categorical (2 vars): chisq.test() or fisher.test().

    • 50+ Numeric variables: Principal Component Analysis (PCA).

  • Principal Component Analysis (PCA):

    • Used to reduce dimensionality in complex datasets.

    • PC1: Axis of maximum variance.

    • PC2: Perpendicular to PC1, captures the next largest variance.

    • Factor Loadings: Correlations between original variables and each PC.

    • Rabbit Example: PC1 represents body SIZE, while PC2 represents body THICKNESS.

    • R Implementation: pca_result <- prcomp(df, scale. = TRUE). Always use scale. = TRUE.

Exam Workflows (Checklists)

  • Linear Regression Cookbook Flow:

    1. State both hypotheses (H0:β1=0H_0: \beta_1 = 0 vs Ha:β1≠0H_a: \beta_1 \neq 0).

    2. Check scatterplot for linearity and outliers.

    3. Analyze 4 diagnostic plots:

      • Residuals vs Fitted: Want horizontal line/starry sky (tests linearity).

      • Q-Q Plot: Want straight diagonal line (tests normality of residuals).

      • Scale-Location: Want straight line with no peaks/valleys (tests equal variance).

      • Residuals vs Leverage: Check Cook's distance (tests influential outliers).

    4. If plots pass, use summary(fit). State r2r^2 and p-value.

    5. Interpret slope: "For every 1-unit increase in X, Y changes by b1b_1 units on average."

    6. Run cor.test(x, y) and report rr, t-stat, p-value, and 95% CI.

    7. Make final statement: Reject/Fail to reject H0H_0.

  • ANOVA Cookbook Flow:

    1. State hypotheses (H0:μ1=μ2=…H_0: \mu_1 = \mu_2 = \dots vs Ha:one differsH_a: \text{one differs}).

    2. Visualize data with a boxplot (stack data if it is in wide format first).

    3. Fit model with aov() and check two diagnostic plots (Q-Q for normality and Scale-Location for equal variance).

    4. Read table via summary(fit); report F-statistic and p-value.

    5. Make final conclusion regarding the group means.

  • Reading influence.measures() Output:

    • cook.d: How much the point shifts fitted values.

    • hat: Leverage (extremeness in X-space). High leverage threshold is >2(p+1)n> \frac{2(p+1)}{n}.

    • inf: Asterisk means the point is flagged by R as potentially influential.