1

Hi I am trying to perform a loop function to in which a new predictor variable is used in each iteration, however I get the following error.

Error in model.frame.default(formula = ~age_c + zglobcog + apoee4_carrier +  : 
  variable lengths differ (found for 'i') 

The data I used can obtained from following google drive spreadsheet.
https://docs.google.com/spreadsheets/d/18yll44P25qsGqgZw4RPTMjlGJ0aNLCp-vYugCD7GPk8/pubhtml

library(nlme)  
snplist <- names(mydata)[5:7]

models <- lapply(snplist, function(x){
   lme(zglobcog ~ age_c + factor(apoee4_carrier) + age_c*factor(apoee4_carrier) + 
   substitute(factor(i) + age_c*factor(i), list(i = as.name(x))), 
   data = mydata, random = ~ age_c | pathid, method = "ML", na.action = na.exclude)
})

I also tried using a for loop and obtained the same error.

for (i in snplist) {
   lme(zglobcog ~ age_c + factor(apoee4_carrier) + 
   age_c*factor(apoee4_carrier) + factor(i) + age_c*factor(i), 
   data = mydata, random = ~ age_c | pathid, method = "ML", na.action = na.exclude)
}

How can I resolve this issue?

Thanks

1 Answer 1

2

After much troubleshooting I was able to resolve this question. The key was to specify what data to use outside of the lme function.

myfunc <- function(x){
out <- with(mydata, lme(zglobcog ~ age_c + factor(apoee4_carrier) + age_c*factor(apoee4_carrier) 
+ factor(i) + age_c*factor(i), random = ~ age_c | pathid, method = "ML", na.action = na.exclude))
out 
}
lapply(mydata[5:7], myfunc)

Or running the function with the lapply inside the function

myfunc <- function(X){
lapply(X, function(.col){
out <- with(mydata, lme(zglobcog ~ age_c + factor(apoee4_carrier) + age_c*factor(apoee4_carrier) 
+ factor(i) + age_c*factor(i), random = ~ age_c | pathid, method = "ML", na.action = na.exclude))
out 
})
}
myfucn(mydata[5:7])

And finally just providing a example using the Orthodont data set

library(nlme)
attach(Orthodont)
head(Orthodont)
myfunc <- function(x){
out <- with(Orthodont, lme(distance ~ age + x, random = ~ age | Subject, method = "ML", na.action 
= na.exclude))
out 
}
myfunc(Sex)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.