1

您好我正在尝试执行一个循环函数,其中在每次迭代中使用一个新的预测变量,但是我收到以下错误。

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

我使用的数据可以从以下 google drive 电子表格中获得。
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)
})

我也尝试使用 for 循环并获得相同的错误。

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)
}

我该如何解决这个问题?

谢谢

4

1 回答 1

2

经过多次故障排除后,我能够解决这个问题。关键是指定要在 lme 函数之外使用哪些数据。

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)

或者在函数内部使用 lapply 运行函数

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])

最后仅提供一个使用 Orthodont 数据集的示例

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)
于 2014-07-29T01:52:19.197 回答