Build logistic regression helpers in R with AIC stepwise selection and scoring
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement binary logistic regression helpers in R around `glm()`, covering fitting, stepwise selection and scoring new data.
- `fit_logistic(data, response, predictors)`: `response` names the 0/1 outcome and `predictors` is a character vector. Fit `response ~ p1 + p2 + ...` with `glm(..., family = binomial())` and return the `glm` object.
- `selected_predictors(data, response, predictors)`: fit the full model and run `step(full, direction = "both", trace = 0)`, which selects by AIC. Return the retained term labels sorted alphabetically, with the intercept excluded, or `character(0)` if none are retained.
- `predict_prob(model, newdata)`: return an unnamed numeric vector from `predict(type = "response")`, one value per row of `newdata`.
- `classify(model, newdata, threshold = 0.5)`: return an integer vector that is `1L` where `predict_prob(model, newdata) >= threshold` and `0L` elsewhere.
Example:
```r
m <- fit_logistic(train, "y", c("x1", "x2", "x3"))
selected_predictors(train, "y", c("x1", "x2", "x3")) # e.g. c("x1", "x3")
predict_prob(m, test) # c(0.12, 0.88, 0.44, ...)
classify(m, test) # c(0L, 1L, 0L, ...)
```
```hint Scale of the predictions
`predict()` on a `glm` object can return values on more than one scale. Check which one gives probabilities.
```
```hint What step() refits
`step()` refits the model many times by re-running its stored call. Think about what happens when dropping a predictor changes which rows have complete data.
```
### Constraints & Assumptions
- The response column holds 0/1 values.
- The solution defines functions only. `library()` calls are allowed.
### What a Strong Answer Covers
- Building the formula from a response name and a character vector of predictors, and fitting with the binomial family
- Running `step()` in both directions and extracting the retained term labels, sorted, including the intercept-only case
- The exact return types: an unnamed numeric vector of probabilities and an integer 0/1 vector
- Pitfalls such as missing values that change the rows used between steps and factor levels in new data that training never saw
- What AIC-based stepwise selection does and where it falls short
### Follow-up Questions
- Why use `direction = "both"` instead of forward or backward only?
- How does `predict(type = "response")` differ from the default link scale?
- How would you evaluate the chosen threshold beyond a fixed 0.5?
- What are the statistical problems with stepwise selection, and what would you use instead?
Overview: Write R helpers around glm() that fit a binary logistic regression, select predictors with an AIC stepwise search through step(), and return probabilities and 0/1 classes for new data. It tests model formulas in R, exact return types and the pitfalls of stepwise selection.