使用粘贴公式创建的 lme 拟合的方差分析测试失败 [英] anova test fails on lme fits created with pasted formula

查看:40
本文介绍了使用粘贴公式创建的 lme 拟合的方差分析测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常通过将我需要的部分粘贴在一起来指定模型拟合函数的公式参数,如 lmlme,如@DWin 对这个问题的回答:了解lm和环境.

I often specify the formula argument to model fitting functions like lm or lme by pasting together the parts I need, as in @DWin's answer to this question: Understanding lm and environment.

实际上这看起来像这样:

In practice this looks like this:

library(nlme)
set.seed(5)
ns <- 5; ni <- 5; N <- ns*ni
d <- data.frame(y=rnorm(N),
                x1=rnorm(N),
                x2=factor(rep(1:ni, each=ns)),
                id=factor(rep(1:ns, ni)))

getm <- function(xs) {
  f <- paste("y ~", paste(xs, collapse="+"))
  lme(as.formula(f), random=~1|id, data=d, method="ML")
}
m1 <- getm("x1")
m2 <- getm(c("x1", "x2"))

但是,使用 nlme 包中的 lme,比较以使用 anova 的方式构建的两个模型不起作用,因为 anova.lme 查看保存的公式参数以确保模型适合相同的响应,保存的公式参数只是 as.formula(f).错误是:

However, with lme from the nlme package, comparing two models constructed in the way using anova doesn't work, because anova.lme looks at the saved formula argument to ensure that the models were fit on the same response, and the saved formula argument is simply as.formula(f). The error is:

> anova(m1, m2)
Error in inherits(object, "formula") : object 'f' not found

这是 anova 命令应该执行的操作(重新调整模型以使其正常工作):

Here's what the anova command should do (refitting the models so that it works):

> m1 <- lme(y~x1, random=~1|id, data=d, method="ML")
> m2 <- lme(y~x1+x2, random=~1|id, data=d, method="ML")
> anova(m1, m2)
   Model df      AIC      BIC    logLik   Test  L.Ratio p-value
m1     1  4 76.83117 81.70667 -34.41558                        
m2     2  8 72.69195 82.44295 -28.34597 1 vs 2 12.13922  0.0163

有什么建议吗?

推荐答案

Ben 的回答有效,但 do.call 提供了他希望的更通用的解决方案.

Ben's answer works, but do.call provides the more general solution he wished for.

getm <- function(xs) {
    f <- as.formula(paste("y ~", paste(xs, collapse="+")))
    do.call("lme", args = list(f, random=~1|id, data=d, method="ML"))
}

它之所以有效是因为(默认情况下)args = 中的参数在传递给 lme 之前被评估.

It works because (by default) the arguments in args = are evaluated before being passed to lme.

这篇关于使用粘贴公式创建的 lme 拟合的方差分析测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆