I am looking for a way to perform "multi-step" regression with broom and dplyr in R. I use "multi-step" as a placeholder for regression analyses in which you integrate in the final regression model elements of previous regression models, such as the fit or the residuals. An example for such a "multi-step" regression would be the 2SLS approach for Instrumental Variable (IV) regression.
My (grouped) data looks like this:
df <- data.frame(
id = sort(rep(seq(1, 20, 1), 5)),
group = rep(seq(1, 4, 1), 25),
y = runif(100),
x = runif(100),
z1 = runif(100),
z2 = runif(100)
)
where id and group are identifiers, y the dependent variable, while x, z1 and z2 are predictors. In a IV setting x would be an endogenous predictor.
Here is an example for a "multi-step" regression:
library(tidyverse)
library(broom)
# Nest the data frame
df_nested <- df %>%
group_by(group) %>%
nest()
# Run first stage regression and retrieve residuals
df_fit <- df_nested %>%
mutate(
fit1 = map(data, ~ lm(x ~ z1 + z2, data = .x)),
resids = map(fit1, residuals)
)
# Run second stage with residuals as control variable
df_fit %>%
mutate(
fit2 = map2(data, resids, ~ tidy(lm(y ~ x + z2 + .y["resids"], data = .x)))
) %>%
unnest(fit2)
This produces an error, which indicates that .x and .y have different lengths. What is a solution to integrate the residuals, in this attempt the .y["resids"], into the second regression as a control variable?