I am carrying out a two-way ANOVA in R to analyse an experiment. I have a long list of moderating variables I need to test for my partner company in the model (mainly numeric, continuous scale items measures).
This would be the basic model of the experiment (without moderators):
model <-lm(data=StudyData, Outcome ~ Factor1*Factor2)
summary.lm(model)
I wondered if there was a quick way I could define a list of moderating variables, and then "swap" in the moderating variables of interest (perhaps using a function), where "Moderator" is defined below:
model <-lm(data=StudyData, Outcome ~ Factor1*Factor2*Moderator)
summary.lm(model)
So for example, the function would run the model once with a certain moderator (e.g. User Age) & print/save the results, then use it again with another moderator (e.g. User Privacy Concern Level) & print/save the results, and so on.
This would be so I can avoid having to manually copy and paste in about 50 moderating variables they are interested in.
Any tips would be greatly appreciated! 🙏.
(small note: I know it may not be exactly scientific to use many moderating variables in a model without theoretical reasons why... but it was requested by the company)
If anyone is looking at this and wants to find a way to do it, I figured it out:
Define a list of moderators, e.g:
modlist <- c("mod1", "mod2", "mod3", "mod4")
Then for each x in modlist, paste the formula in you want to use. Optional print commands tell you what y variable you selected in your model (as a reminder), and print x shows results for each model.
for (x in modlist) {
lmfit <- lm(as.formula(paste("Outcome ~ Factor1*Factor2*",x)), data= StudyData)
print("y=Outcome")
print(x)
print(summary.aov(lmfit))
}