I am not sure that "list" is the right word, but I knew how to do this but lost the code. I have multiple models I would like to illustrate with stargazer. Instead of typing every single model, I would like to put them into a list that I can then Stargazer and be done with it. Right now I have:
model1 <- lm(Dependent ~ Variable1 Variable2 Variable3, Variable4, data = dataset)
model2 <- lm(Dependent ~ Variable5 Variable2 Variable3, Variable4, data = dataset)
model3 <- lm(Dependent ~ Variable6 Variable2 Variable3, Variable4, data = dataset)
model4 <- lm(Dependent ~ Variable7 Variable2 Variable3, Variable4, data = dataset)
model5 <- lm(Dependent ~ Variable8 Variable2 Variable3, Variable4, data = dataset)
I would like to put all these models into a "list", let's say, "List1" so that I can then do Stargazer(List1)
and visualize these.
*Edited a mistake in the formula that had a comma instead of a plus sign -- but this was not part of the question. Just edited for clarity.
CodePudding user response:
I find it easier to work with strings than formula objects, so I tend to build strings for my model formulas and then use as.formula
to turn them into formula objects for modeling.
In your case, something like this:
first_var = paste0("Variable", c(1, 5, 6, 7, 8))
formulas = sprintf("Dependent ~ %s Variable2 Variable3 Variable4", first_var)
models = list()
for(i in seq_along(formulas)) {
models[[first_var[i]]] = lm(as.formula(formulas[i]), data = dataset)
}
This will create a list models
with names Variable1, Variabl5, ...
containing model objects with corresponding formulas.
CodePudding user response:
I have finally found the answer. For anyone who is lurking, this is how you lump multiple models under a list to then illustrate with Stargazer or something else:
name_of_your_choice <- list(model1, model2, model3)