【问题标题】:Looping in nlme在 nlme 中循环
【发布时间】:2014-07-15 01:52:31
【问题描述】:

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

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

我该如何解决这个问题?

谢谢

【问题讨论】:

    标签: r loops lapply nlme


    【解决方案1】:

    经过多次故障排除后,我能够解决这个问题。关键是指定要在 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-28
      • 2018-07-26
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      相关资源
      最近更新 更多