I would like to run a series of regression models and put the output relating to a particular covariate into an array. I've been able to do this with laply from the plyr package, like this:
set.seed(1)
df <- data.frame(x1 = rnorm(100, 0, 1),
x2 = rnorm(100, 0, 1),
y1 = rnorm(100, 0, 1),
y2 = rnorm(100, 0, 1),
t2 = sample(0:1, 100, replace = TRUE),
t1 = sample(0:1, 100, replace = TRUE))
run_regressions <- function(model) {
model <- glm(model, data = df)
return(summary(model)$coefficients[2,])
}
models <- list("y1 ~ t1 + x1",
"y2 ~ t2 + x1 + x2")
results <- laply(models, run_regressions)
results
I would now like to extend this so that I can pass the different elements of the regression models to the run_regressions function separately. The regression function would be defined like
run_regressions2 <- function(outcome, treatment, covariates) {
model <- glm(paste(outcome, " ~ ", treatment, " + ", covariates), data = df)
return(summary(model)$coefficients[2,])
}
with the specific models to run specified as something like
models <- list(c("y1", "t1", "x1"),
c("y2", "t2", "x1 + x2"))
Is there some way to use laply or another function to achieve this?
I've tried searching the plyr documentation for similar examples and searching SO for similar questions, but have not come up with anything.
As mentioned by @jdobres ,
plyrhas been long retired. There are lot of modern replacements for it likedplyrandpurrrpackage.One option would be to use
lapplyin base R. In such case, the first case would change toIn the second, case you can continue using
lapply-Or more generally using
do.callfor any number of arguments.