Looping in nlme

扶醉桌前 提交于 2019-12-11 05:05:41

问题


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:


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)


来源:https://stackoverflow.com/questions/24748724/looping-in-nlme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!