Extracting Model Outputs - R Programming
- For a training observation with
x = 2, which value should appear infitted(fit)?Answer: When working with polynomial regression in R, the key is understanding howlm()interprets each term in the formula and how those terms map to the prediction equation. The modely ~ x + I(x^2)fits three parameters: an intercept, a coefficient for , and a coefficient for — each applied to their respective terms independently. With coefficients(Intercept) = 1,x = 2, andI(x^2) = -0.5, the fitted value at is simply: That confirms D is correct. Now let's see where the wrong answers go astray. A applies the coefficient directly to rather than squaring first — it computes instead of , mixing up which term gets squared. B combines the two slope coefficients and applies them together to , treating the model as if it had a single compound coefficient rather than two separate terms — a structural misreading of the formula. C swaps the roles of the coefficients entirely, applying to and to , which reverses the model structure. The study tip here: always match each coefficient to its exact term. In R,I(x^2)creates a standalone column of squared values — its coefficient multiplies , not . Write out explicitly before plugging in numbers to avoid misassignment errors. - Ignoring any other predictors, what fitted value does
fitted(fit)assign to an observation in groupC?Answer: , because the intercept and thegroupCcoefficient are added. Whenever you encounter a question about fitted values in a linear model with factor predictors, your first instinct should be to recall how treatment (dummy) coding works: every fitted value is built by adding the intercept to the relevant group coefficient. In treatment contrasts, R automatically designates one factor level as the reference group — here, groupA(the first level alphabetically). The intercept represents the mean of that reference group. Each subsequent coefficient represents the difference from that reference. So for an observation in groupC, the fitted value is: That makes D the correct answer. A is wrong becausegroupC = 3alone is just the difference from groupA, not the actual predicted value. Ignoring the intercept gives you an incomplete picture. B is wrong because it subtracts the coefficient from the intercept (), which has no basis in the model formula. There is no subtraction happening here — the coefficient is simply added. C is wrong because the intercept () applies only to the reference group (A). Saying the intercept is used for every level conflates the baseline with the full prediction for non-reference groups. A useful rule of thumb: always write out the model equation explicitly — — and plug in for the relevant group. This prevents both the "intercept-only" and "coefficient-only" traps. - Which pair correctly gives the fitted value from
fitted(fit)and the default value frompredict(fit)for that observation?Answer:fitted(fit)gives , andpredict(fit)gives . Whenever you work with GLMs in R, you need to track two distinct scales: the linear predictor (the raw output of ) and the response scale (the predicted mean after applying the inverse link function). For this Poisson model with a log link, the linear predictor at is . The inverse of the log link is the exponential, so the response-scale prediction is .fitted(fit)always returns values on the response scale — the predicted counts in this case — so it gives . Meanwhile,predict(fit)with notypeargument defaults totype = "link", meaning it returns the linear predictor: . This makes B correct. Choice A has the two scales swapped — it assigns the linear predictor tofitted()and the response topredict(), which is exactly backwards. Choice C invents an incorrect formula () by misapplying the intercept as if it weren't inside a logarithm, and the expression forpredict()has no mathematical basis in this model. Choice D splits the exponential incorrectly across the two coefficients — the inverse link applies to the entire linear predictor as a sum, not term by term. A handy rule: **fitted()= response scale,predict()default = link scale.** If you wantpredict()on the response scale, you must explicitly writepredict(fit, type = "response"). Memorize this distinction — it's a frequent trap in R GLM questions. - Which expression extracts only the p-value for the coefficient of
x?Answer:coef(summary(fit))["x", "Pr(>|t|)"]When working with linear model output in R, it helps to think in layers:lm()stores a model object,summary()computes inferential statistics from it, and subsetting functions likecoef()or$extract specific pieces. The p-values live in the summary layer, not the model layer itself. To grab the p-value forx, you need to reach into the coefficient matrix thatsummary()produces. That matrix is accessible viasummary(fit)$coefficients(or equivalentlycoef(summary(fit))), and it has both row names (one per predictor) and column names including"Pr(>|t|)". Socoef(summary(fit))["x", "Pr(>|t|)"]pinpoints exactly the cell at row"x"and the p-value column — making B correct. Here's why the other options miss the mark. A usescoef(fit), which extracts coefficients from the model object itself — this returns only the point estimates (theEstimatecolumn), not any inferential statistics. You'd just get a single number like2.34, not a p-value. C also accesses the right summary matrix, but requests the"Estimate"column instead of"Pr(>|t|)"— so it returns the coefficient estimate, not the p-value. It's a near-miss that tests whether you know the column names. D usesfitted(fit), which returns the model's fitted values (predicted ŷ for each observation in the dataset) — completely unrelated to coefficient-level statistics. A handy tip: whenever you need anything beyond point estimates — standard errors, t-statistics, or p-values — always go throughsummary(fit)$coefficientsand double-bracket with both row and column names. - Which set of expressions extracts exactly those three outputs? Answer:
summary(fit)$adj.r.squared,coef(fit)[["x"]], andfitted(fit)When working with fitted linear models in R, you need to know which extractor functions and named list elements pull out specific summaries. This question tests your familiarity withsummary(fit),coef(), and the generic model extractors. For adjusted , the correct field insidesummary(fit)is$adj.r.squared— this is the exact name R uses internally. The estimated slope forxis cleanly retrieved withcoef(fit)[["x"]], which indexes the named coefficient vector by predictor name. Finally,fitted(fit)returns the vector of predicted values on the training data. Together, these three expressions make A the correct and complete set. Here's why the distractors fail. B retrieves$r.squaredinstead of$adj.r.squared— that gives you the ordinary , not the adjusted version, which penalizes for extra predictors. C uses$adjusted.r.squared, which simply doesn't exist as a field name in R's summary output — it will returnNULLrather than an error, making it a silent bug. C also swapsfitted(fit)forresiduals(fit), which returns , not the fitted values themselves. D usessummary(fit)$coefficients["x", 2], which extracts the standard error of the slope (column 2 of the coefficients table), not the estimate (column 1) — a subtle but meaningful distinction. As a study tip, memorize the exact field names insummary(lm(...)):$r.squared,$adj.r.squared, and$coefficients. When you need just the point estimate of a coefficient, prefercoef()over indexing the summary table to avoid column-order confusion. - Which statement correctly describes the coefficient and fitted-value outputs for this observation? Answer:
coef(fit)has no estimated coefficient forz, and the fitted value is . When you useoffset()in a linear model, you're telling R to include a variable with a fixed coefficient of 1 rather than estimating one from the data. This is fundamentally different from a regular predictor — the offset shifts predictions without consuming a degree of freedom or appearing incoef(). Becausezis wrapped inoffset(), R never estimates a coefficient for it. Socoef(fit)returns only the intercept and the slope forx— no entry forzat all. The fitted value for any observation is computed as: This confirms C is correct: no estimated coefficient forz, and a fitted value of . A is wrong on both counts — it claimscoef(fit)contains a coefficient of forz, but offsets are never estimated and never appear incoef(). The value is the observed value ofz, not a coefficient. B similarly invents a coefficient of forz; while is indeed the implicit multiplier an offset uses, R does not report it as an estimated coefficient incoef(). D gets the coefficient story right — no entry forz— but miscalculates the fitted value by omitting the offset entirely: ignoresz's contribution. A good rule of thumb: **offset()means "fixed at 1, not reported."** Whenever you seeoffset(z)in a model formula, expectcoef()to be silent about it, but always includezin your fitted-value calculation. - What values do
fitted(fit)andresiduals(fit)contain for this row?Answer: The fitted value is , and the residual is . When working with weighted regression in R, it's crucial to understand what the weights actually affect — and what they don't. Weights inlm()influence how much each observation contributes to estimating the coefficients, but they do not scale the fitted values or raw residuals themselves. Once the model is fitted,fitted(fit)simply plugs each row's predictor values into the regression equation: . For this row, that gives . Thenresiduals(fit)computes the ordinary difference . So the correct answer is A. Choice B multiplies the fitted value by the weight () and computes a correspondingly distorted residual. This confuses the role of weights — they enter the loss function during estimation, not the prediction step. Choice C gets the fitted value right () but then multiplies the residual by the weight (), again misapplying where weights matter. Choice D multiplies both and the fitted value by the weight before computing the residual, compounding the same misconception. A helpful rule of thumb: **weights change how the line is fit, not what the line predicts**. After fitting,fitted()andresiduals()behave identically to unweighted regression — it's only functions likeweighted.residuals()or the internal WLS math that incorporate the weights explicitly. Keep this distinction clear and you'll avoid all three traps above. - Which expression extracts the estimates in the required form? Answer:
coef(summary(fit))[, "Estimate", drop = FALSE]When subsetting a matrix in R, you need to understand how thedropargument controls whether dimensions are preserved. By default, extracting a single row or column from a matrix drops that dimension, returning a named vector instead of a one-column (or one-row) matrix. When a downstream function strictly requires matrix input, you must suppress this behavior withdrop = FALSE.coef(summary(fit))returns a matrix where rows are predictor terms and columns are"Estimate","Std. Error","t value", and"Pr(>|t|)". Option C,coef(summary(fit))[, "Estimate", drop = FALSE], correctly selects the"Estimate"column while keeping the result as a matrix — exactly what the question requires. Option A,coef(summary(fit))[, "Estimate"], is the most tempting distractor. It extracts the same values, but withoutdrop = FALSE, R collapses the result into a plain named vector. This breaks any function expecting a matrix. Option B,coef(fit)["Estimate", drop = FALSE], has two problems:coef(fit)returns a simple named vector of coefficients (not a matrix), and"Estimate"is not a valid index for it — the names are"(Intercept)"and"x". Thedrop = FALSEargument is also irrelevant when subsetting a vector. Option D,summary(fit)$coefficients["Estimate", ], attempts to subset a row named"Estimate", but no such row exists —"Estimate"is a column name, not a row name. A good habit: whenever matrix structure must be preserved through subsetting, always reach fordrop = FALSEas your default defensive practice.