Home > Software engineering >  Q: R how to loop moderation analysis
Q: R how to loop moderation analysis

Time:02-08

I want to perform several moderation analyis on the relationship between my independent variable (x) and the dependent variable (y). I have a dataset (myData) with the variables x, y and numerous moderators (a, b, c, d, e). Here the code:

for(i in 2:ncol(QBSData)){
    mod_name <- colnames(MyData)[i]
    mod_summaries[[i-1]]<-summary(
    lm(y ~ x   MyData[, c(mod_name)]   x * MyData[, c(mod_name)], data = MyData))
}
mod_summaries

The code is working, but I would like to have the name of the moderator (e.g. a, b, c...) as name of the model when displaying the results.

Any suggestions on how can I implement this feature and improve the code to loop the moderation analysis?

Thank you in advance!

CodePudding user response:

I think you need the assign function:

a <- c("model1", "model2", "model3")
assign(a[1], 5)
#> model1
#[1] 5

#you name the moderator in a vector already, I believe (mod_name). So you need to add the following to your code:

slm <- summary(lm(y ~ x   MyData[, c(mod_name)]   x * MyData[, c(mod_name)], data = MyData))

assign(mod_name, slm)
``
  •  Tags:  
  • Related