【问题标题】:Issue with formula environment公式环境问题
【发布时间】:2016-01-22 06:18:30
【问题描述】:

下面的代码包含一个显示我的问题的简化示例。不是那么简单,但我不想删除太多的上下文。

当我使用 as.formula() 创建公式并尝试使用该公式来拟合模型以乘以估算数据时,我得到“eval(expr, envir, enclos) 中的错误:找不到对象'结果'” .当我在建模语句(最后一行)中明确列出公式时,没问题。此外,如果我在单个数据集的分析中引用该公式(即,不需要'with'),也没有问题。问题似乎很明显,该公式是在全局环境中创建的,而我需要它在数据框中查找命名变量。我只是不太了解 R 环境,无法弄清楚如何解决这个问题。

我在几个场景下使用一组更复杂的模型在模拟中应用此代码,因此如果我要高效地对这些模拟进行编程,我下面的最后一行代码并不是一个真正的选择。

感谢您的建议!

library(MASS)
library(mitools)
library(lme4)

#Generate 3 small datasets to emulate multiply imputed data
Sigma <- matrix(c(1, 0.5, -0.7, -0.4, -0.4,
                  0.5, 1, -0.4, -0.2, -0.2, 
                  -0.7, -0.4, 1, 0.5, 0.4, 
                  -0.4, -0.2, 0.5, 1, 0.6,
                  -0.4, -0.2, 0.4, 0.6, 1),5,5)

complete <- as.list(1:3)
for (i in 1:3){
  complete[[i]] <- as.data.frame(mvrnorm(n = 10, mu=c(0,0,0,0,0), Sigma=Sigma))
}


#Convert to longitudinal analysis format and imputationList object type
all.long <- imputationList(lapply(complete, reshape, varying=c("V3", "V4", "V5"), direction="long", 
                                   v.names="outcome", times=c(0,2,4)))

current.formula <-formula(outcome ~ 1 + time + (1 | id) + (0 + time | id) + V1 + V2)

#This does not work:
imp.fit <- with(data=all.long, lmer(current.formula, REML=TRUE))
# Error in eval(expr, envir, enclos) : object 'outcome' not found


# This does work:
imp.fit <- with(all.long, lmer(outcome ~ 1 + time + (1 | id) + (0 + time | id) + V1 + V2, REML=TRUE))

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以在估算的 data.frames 列表中使用 lapply:

    current.formula <- formula(outcome ~ 1 + time + (1 | id) + (0 + time | id) + V1 + V2)
    imp.fit2 <- lapply(all.long$imputations, function(dat) lmer(current.formula, REML=TRUE, data=dat))
    

    这将为您提供与直接调用公式时完全相同的结果。

    【讨论】:

    • 谢谢,@htfy。我需要在我的桌子上挂个牌子,提醒我在更多情况下考虑 lapply。但是,如果可能的话,我希望保留一个多重插补对象类型,以方便使用 MIcombine 之类的函数来汇集结果,而无需额外的步骤来将结果强制转换为正确的结构。
    • @JBeau:哪个对象想要具有多重插补类型?据我所知,imp.fitimp.fit2 的元素具有相同的类型。你可以使用mitools 函数:例如MIextract(imp.fit2, fun=fixef) 应该可以工作。有关示例,请参见 this
    • 啊,你说得对。谢谢!附言我意识到为时已晚,我应该在对我的问题进行额外编辑之前接受您的编辑,以便您获得声誉积分。对不起!
    猜你喜欢
    • 2012-02-20
    • 2022-01-18
    • 2019-06-09
    • 2019-05-29
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多