I want to use the same regression model for each group and use the coefficients (different across groups) to add predicted values in the same data set. I can do it using a loop, but how can I do it with lapply?
data <- data.frame(x = rnorm(100), y = rnorm(100), id = rep(c('a', 'b', 'c', 'd'), 25))
for (i in unique(data$id)){
model <- lm(y ~ x, data = subset(data, id == i))
data$pred[data$id == i] <- predict(model, subset(data, id == i))
}