I tried to build this Loop so that I can test two outcomes at the same time. However, it produced an error message: "Error in model.frame.default(formula = ~outcome centered.predictor1 : variable lengths differ (found for 'centered.predictor1')"
But when I tested each outcome separately, the code (without loop) didn't produce errors.
Thanks in advance for your help!
n1 = rnorm(n = 2000, mean = 0, sd = 1)
n2 = rnorm(n = 2000, mean = 0, sd = 1)
Z_familism = rnorm(n = 2000, mean = 0, sd = 1)
Z_avoidance = rnorm(n = 2000, mean = 0, sd = 1)
Country = rnorm(n = 2000, mean = 0, sd = 1)
Z_anxiety = rnorm(n = 2000, mean = 0, sd = 1)
data01<-data.frame(n1,n2,Z_familism,Z_avoidance,Country,Z_anxiety)
outcome<-c('n1', 'n2')
for (n in outcome){
rsa.data<-data.frame(predictor1=data01$Z_familism,
predictor2=data01$Z_avoidance,
nest=as.factor(data01$Country),
control=data01$Z_anxiety,
multilevel=data01$Country,
outcome=data01[n])
rsa.data <- within.data.frame(rsa.data, {
centered.predictor1 <- predictor1 - 0 #Center predictor 1
centered.predictor2 <- predictor2 - 0 #Center predictor 2
squared.predictor1 <- centered.predictor1* centered.predictor1 #Create squared term
squared.predictor2 <- centered.predictor2* centered.predictor2 #Create squared term
interaction <- centered.predictor1* centered.predictor2 #Create interaction term
})
mlm.model <- lme(outcome ~ centered.predictor1 centered.predictor2 squared.predictor1 interaction squared.predictor2 control,
data = rsa.data,
random = ~ 1|multilevel, # Replace "nesting.variable" with the name of your nesting variable
na.action = "na.omit")
summary(mlm.model) #View Model
intervals(mlm.model, which = "fixed")
vcov(mlm.model) #View covariance of model
}
CodePudding user response:
The problem is when you create the rsa.data dataframe inside the loop, specifically with the outcome column. Instead of data01[n] which returns a dataframe, you should use data01[, n], which returns a numeric vector. That way all your data has the same length.
rsa.data<-data.frame(predictor1=data01$Z_familism,
predictor2=data01$Z_avoidance,
nest=as.factor(data01$Country),
control=data01$Z_anxiety,
multilevel=data01$Country,
outcome=data01[, n])