Linear Models (lm) - R Programming
- For a fitted model
fit <- lm(y ~ x, data = d), an analyst usespredict(fit, newdata = data.frame(x = 10), interval = "confidence"). The analyst instead needs an interval for a single future response observed atx = 10. Which change and interpretation are appropriate, assuming the usual linear-model conditions?Answer: Useinterval = "prediction"; its center is the same, but its interval is generally wider. Whenever you see a question aboutpredict()in R, ask yourself: am I estimating the mean response at a given x, or am I predicting one new individual observation? These require different intervals, and confusing them is one of the most common modeling mistakes. A confidence interval (CI) for the mean captures uncertainty about where the true average response falls at x = 10. A prediction interval (PI) captures that same uncertainty plus the natural scatter of individual observations around the mean — represented by the residual variance . Formally, the CI width depends on , while the PI adds underneath the square root: Notice the extra "1" inside the square root — that single term is what widens the prediction interval. Critically, both intervals share the same center ; only the width differs. This makes C correct: switching tointerval = "prediction"keeps the point estimate identical but produces a wider interval, as required for a single future observation. A is wrong because a confidence interval does not account for individual-response variability — it only reflects uncertainty about the mean. B is wrong on two counts: the center does not change between CI and PI, and prediction intervals are wider, not narrower, than confidence intervals. D is wrong because the two intervals are numerically distinct; only their centers coincide. As a study tip, remember: "confidence" → mean, "prediction" → individual. Same center, PI is always wider. - An analyst fits
lm(log(y) ~ x, data = d)and obtains an intercept of and anxcoefficient of . According to the fitted equation, what is the effect of increasingxby units on the back-transformed fitted value?Answer: The fitted value is multiplied by , which is approximately . Whenever you fit a log-transformed response model likelm(log(y) ~ x), you need to remember that predictions live on the log scale, and back-transformation requires exponentiation — not simple arithmetic. The fitted equation on the log scale is . When you increase by 3, the log-scale prediction changes by . To understand the multiplicative effect on itself, consider two predictions at values and : The intercept cancels out completely in the ratio. So the fitted value is multiplied by , confirming B is correct. A is wrong because a change on the log scale does not transfer additively to the original scale — you must exponentiate. C incorrectly includes the intercept () in the multiplicative effect. Since you're measuring a change between two predictions, the intercept cancels — it shifts both values equally. D tempts you with the "log ≈ percent change" approximation, which only holds for very small changes; a log-scale shift of 0.3 corresponds to a 35% increase (), not 30%. As a study tip, always take the ratio of two back-transformed predictions when assessing a unit-change effect in log-linear models — intercepts vanish and only the slope-driven term remains. - Suppose
grouphas levelsAandB, and an analyst fitslm(y ~ 0 + group + x). The estimated coefficients aregroupA,groupB, andx. Which interpretation is correct?Answer: At the fitted values are and , and their difference of is constant for every value of . When you seelm(y ~ 0 + group + x)in R, recognize that suppressing the global intercept with0causes R to estimate a separate intercept for each factor level rather than one shared baseline. Eachgroupcoefficient becomes that group's fitted value of when , and the slope onxapplies equally to both groups. With coefficientsgroupA,groupB, andx, the fitted value equations are: At , group A fits to and group B fits to . Because both lines share the same slope of , their vertical distance stays at for every value of . That makes B the correct interpretation. A is wrong because the group coefficients here are adjusted baselines (controlling for ), not raw sample means — and the claim that the difference "applies only at " is misleading; since the slope is shared, the difference is constant everywhere. C is wrong because removing the intercept does not force group A's fitted value to zero — it simply gives each group its own intercept estimated from the data. D reflects a confusion with treatment-coded (dummy) models, where one group's coefficient is added to a reference intercept; in a no-intercept model,groupAandgroupBare independent, not cumulative. As a quick rule of thumb: in~ 0 + factor, every level gets its own intercept — they are never added together. - In every row of a data frame,
x2equals exactly twicex1. An analyst fitslm(y ~ x1 + x2, data = d). Which outcome best describes the fitted model?Answer: At least one slope is not separately estimable due to linear dependence in the model matrix, though fitted values can still be produced from an equivalent reduced-rank solution. Whenever you see a question involving predictors with an exact linear relationship, your first instinct should be to think about the rank of the model matrix and what that means for identifiability of coefficients. Here, since in every row, the model matrix columns are perfectly collinear. R'slm()detects this rank deficiency and drops one redundant predictor (typicallyx2), setting its coefficient toNA. This means the two slopes cannot be separately identified — infinitely many combinations of and satisfying produce identical fitted values. The model still runs and still produces fitted values (and predictions) using the reduced-rank solution, which is exactly what D describes. A is wrong becauselm()does not automatically standardize predictors before solving the normal equations. Even if it did, standardizing perfectly collinear columns wouldn't break the dependence — they'd still be proportional. B is wrong becauselm()does return a solution; it simply drops the linearly dependent column and estimates the remaining coefficients. Coefficients are not forced to zero, and no error is thrown — just a warning and anNAfor the dropped term. C is wrong because the intercept is unaffected by collinearity among predictors. The intercept is estimated normally; it's the slopes that become non-uniquely estimable, not the intercept. Study tip: When you see "exact collinearity" in a question, remember the key consequence: fitted values are still valid, but individual slopes are not separately identifiable. Always checksummary(model)forNAcoefficients as your diagnostic signal. - A model
lm(y ~ x1 + x2)is fit using complete observations. Its residual sum of squares is , and the total sum of squares around the sample mean is . Which pair gives the model's multiple and adjusted , respectively?Answer: Multiple and adjusted . Whenever you see a question combining RSS, TSS, and model degrees of freedom, you need two formulas: one for and one for adjusted . **Multiple ** measures the proportion of total variation explained by the model: **Adjusted ** penalizes for the number of predictors relative to sample size : Here, , (two predictors: x1 and x2), so: This confirms C is correct. Choice A flips the interpretation entirely — it reports as instead of , getting both values wrong. Choice B gets right but miscalculates adjusted as , likely by using the wrong degrees of freedom (perhaps instead of in the denominator). Choice D correctly identifies but sets adjusted equal to it, ignoring the penalty for predictors entirely. A reliable tip: adjusted is always less than when you have at least one predictor, so any answer where they're equal (like D) should immediately raise a flag. - A data frame has rows. For
lm(y ~ x, data = d),yis missing in rows and , whilexis missing in rows and . A separate variablez, which is not in the formula, is missing in row . Using the default missing-value handling, what residual degrees of freedom should the fitted model have?Answer: residual degrees of freedom, because only rows missingyorxare dropped, leaving nine complete cases from which two coefficients are estimated. Whenever you see a question aboutlm()and missing data in R, the key concept to recall is **na.action = na.omit**, which is the default behavior. Under this rule, R drops any row that is missing a value for a variable actually used in the formula — and only those rows. Here, the formula isy ~ x, so R checks columnsyandxforNAs. Row 2 is missingy, row 7 is missing bothyandx, and row 9 is missingx. That gives three distinct rows removed: rows 2, 7, and 9. The variablezis not part of the formula, so row 10 is untouched. Starting from 12 rows, dropping 3 leaves 9 complete cases. Fittinglm(y ~ x)estimates 2 coefficients (intercept and slope), so residual degrees of freedom . Answer B is correct. Answer A is wrong because it counts four "missing entries" as four dropped rows — but rows 2 and 7 share the same observation, and missing entries, not rows, were counted. Answer C incorrectly includes row 10 (missingz) in the exclusion, and its logic about row 7 being "counted twice" misunderstands howna.omitworks: a row is dropped once regardless of how many of its formula variables areNA. Answer D is wrong in the opposite direction — it claims onlyy-missing rows are dropped, ignoring that missing predictor values (xin row 9) also trigger omission. A useful rule of thumb: R's defaultna.omitperforms casewise (listwise) deletion on formula variables only — count unique rows affected, then subtract coefficients. - An analyst fits
fit <- lm(score ~ hours + prior, data = d). The estimated intercept is , the coefficient ofhoursis , and the coefficient ofprioris . Student 1 hashours = 4andprior = 60; Student 2 hashours = 2andprior = 68. According to the fitted model, how do their predicted scores compare?Answer: Student 1's predicted score is points higher than Student 2's. When working with multiple regression predictions, your job is to plug each student's values into the fitted equation: . Here, that means . For Student 1: . For Student 2: . Student 1 scores 2 points higher, confirming A is correct. The traps in the wrong answers are worth understanding. B claims a 10-point difference — this likely comes from only comparing thehourseffect: Student 1 studies 2 more hours, so extra points fromhours, but you must also account for thepriordifference. Student 2 has 8 more prior points, contributing extra points, which partially offsets Student 1's advantage: , not 10. C reverses the direction — Student 2 does benefit more fromprior, but not enough to overcome Student 1's largerhoursadvantage. D is tempting because the predictors do partially offset each other, but "exactly" is wrong; the net difference is 2 points, not zero. A useful habit: when comparing two observations, calculate the difference in each predictor, multiply by its coefficient, then sum. Here, . This shortcut saves time and reduces arithmetic errors. - An analyst fits
fit <- lm(y ~ x + z, data = d)and obtains the fitted equation . For one row, , , and the observed response is . What are the fitted value and ordinary residual for that row?Answer: The fitted value is , and the residual is . When working with linear regression output in R, you need to distinguish between two separate calculations: the fitted value (what the model predicts) and the residual (how far off that prediction is from reality). To find the fitted value, simply plug the predictor values into the estimated equation. With , substituting and gives: The residual is then computed as observed minus fitted: So the fitted value is 11 and the residual is 7, making D the correct answer. Choice A is tempting if you confuse the fitted value with the observed value — the fitted value is what the model predicts, not what was actually measured. Choice B gets the fitted value right (11) but flips the sign of the residual by computing instead of . This is a very common sign error. Choice C likely results from an arithmetic mistake — perhaps forgetting to subtract 's contribution correctly and arriving at 17 instead of 11. A useful memory aid: residual = Real minus Regression (observed minus fitted). The sign matters — a positive residual means the model underpredicted, and a negative residual means it overpredicted. On regression questions in R, always double-check your plug-in arithmetic and keep the subtraction order straight. - A factor
treatmenthas levelscontrol,drugA, anddrugB, withcontrolas the reference level. Forlm(response ~ treatment), the estimated coefficients are: intercept ,treatmentdrugA, andtreatmentdrugB. IfdrugBis made the reference level and the model is refitted, which coefficients should result?Answer: Intercept ,treatmentcontrol, andtreatmentdrugA. When working with linear models in R, the intercept always represents the mean of the reference level, and each treatment coefficient represents the difference from that reference. Changing the reference level doesn't change the underlying group means — it just re-expresses the same relationships from a different baseline. From the original model, you can recover the three group means directly: control , drugA , and drugB . These are fixed facts about your data. When drugB becomes the reference level, the new intercept must equal drugB's mean: . The coefficient fortreatmentcontrolis then , andtreatmentdrugAis . That gives you intercept ,treatmentcontrol,treatmentdrugA— exactly answer A. Answer B is a trap: it keeps the original intercept of and coefficients unchanged, which would only be correct if the reference level hadn't changed. Answer C gets the intercept right () but incorrectly reuses the old coefficients without adjusting them to the new baseline — a common half-step error. Answer D appears to confuse coefficients with raw means in a scrambled way, producing nonsensical values that don't correspond to any coherent model. A reliable strategy: always recover the group means first, then rebuild from the new reference. The means never change; only the arithmetic used to express them does. In R, userelevel(treatment, ref = "drugB")before refitting to let R handle this automatically. - A model is fit with
lm(y ~ x * group), wheregrouphas reference levelAand comparison levelB. The estimated coefficients are: intercept ,x,groupB, andx:groupB. For an observation in group B, how much does the fitted response change whenxincreases from to ?Answer: It increases by because the group B slope is . When a model includes an interaction term likex * group, the slope ofxis not the same for all groups — it depends on which group an observation belongs to. Your job is to find the effective slope for the specific group in question, then multiply by the change inx. For group B, the effective slope ofxis the reference-group slope plus the interaction coefficient: . Whenxincreases from to , that's a change of . The predicted change in response is , so the fitted value increases by . That confirms A is correct. Here's why each distractor fails. B uses the reference-group slope of and computes , but that slope applies to group A only — it ignores the interaction term entirely, which is exactly the trap the question is setting. C focuses only on the interaction coefficient and multiplies it by to get , confusing the adjustment to the slope with the slope itself; the interaction term modifies the slope, it doesn't replace it. D adds thegroupBmain effect () into the slope calculation, but main effects shift the intercept for group B, not the slope — thegroupBcoefficient is irrelevant when calculating how much the response changes withx. A useful rule of thumb: when computing change in ŷ, intercept-type terms (including group main effects) cancel out. Only terms involvingxmatter — so always build the effective slope first, then multiply by .