I want to use the same regression model for each group (id) using data "train" and use the estimated coefficients to create predicted values in data "test". I can do it using a loop, but how can I do it with lapply or something else?
train <- data.frame(x = 1:100, y = rnorm(100), id = rep(c('a', 'b'), 50))
test <- data.frame(x = 1:50, id = rep(c('a', 'b'), 25))
for (i in c('a', 'b')){
model <- lm(y ~ x, data = subset(train, id == i))
test$pred[test$id == i] <- predict(model, subset(test, id == i))
}