在nlme中循环 [英] Looping in nlme
问题描述
我正在尝试执行一个循环函数,在每次迭代中都使用一个新的预测变量,但是出现以下错误.
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')
我使用的数据可以从以下Google驱动器电子表格中获取.
https://docs.google.com/spreadsheets/d/18yll44P25qsGqgZW4RPM
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)
})
我也尝试使用for循环并获得相同的错误.
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)
}
如何解决此问题?
谢谢
推荐答案
经过大量的故障排除后,我能够解决此问题.关键是要指定要在lme函数之外使用的数据.
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)
或者在函数内部使用lapply来运行函数
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])
最后仅提供使用Orthodont数据集的示例
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)
这篇关于在nlme中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!