【问题标题】:Using a matrix of predictors with lmer()使用带有 lmer() 的预测变量矩阵
【发布时间】:2012-09-26 02:01:48
【问题描述】:

我正在尝试用大量预测变量拟合模型,这样在模型公式中枚举它们会很乏味。使用 lm() 很简单:

indicatorMatrix <- data.frame(matrix(rbinom(26000, 1, 1/3), ncol = 26))
colnames(indicatorMatrix) <- LETTERS
someDV <- rnorm(nrow(indicatorMatrix))

head(indicatorMatrix) 

# One method, enumerating variables by name:
olsModel1 <- lm(someDV ~ A + B + C + D,  # ...etc.
               data = indicatorMatrix)

# Preferred method, including the matrix of predictors:
olsModel2 <- lm(someDV ~ as.matrix(indicatorMatrix))
summary(olsModel2)

由于我有大量的预测变量(超过本发明示例中的 26 个),我不想像第一个示例 (someDV ~ A + B + C + D...) 那样单独列出它们,我可以通过以下方式避免这种情况包括预测变量as.matrix

但是,我想拟合一个混合效果模型,如下所示:

library(lme4)
meModel1 <- lmer(someDV ~ (1 | A) + (1 | B) + (1 | C),  # ...etc.
                 data = indicatorMatrix)
summary(meModel1)

除了我想包含大量随机效应术语。我不想输入(1 | A) ... (1 | ZZZ),而是希望以类似于上面olsModel2 使用的矩阵方法的方式包含每个预测变量。显然,以下内容不起作用:

meModel2 <- lmer(someDV ~ (1 | as.matrix(indicatorMatrix)))

对于如何使用 lmer() 最好地复制矩阵预测器方法以获得随机效应,您有什么建议吗?我非常愿意考虑“实用”的解决方案(即黑客),只要它们是“程序化的”并且不需要我复制和粘贴等。

提前感谢您的宝贵时间。

【问题讨论】:

    标签: r lme4


    【解决方案1】:

    认为将公式构造为字符串,然后使用as.formula,类似于

    restring1 <- paste0("(1 | ",colnames(indicatorMatrix),")",collapse="+")
    form <- as.formula(paste0("someDV ~",restring1))
    meModel1 <- lmer(form, data = data.frame(someDV,indicatorMatrix))
    

    应该可以工作(无论如何,它在我的系统上运行而不会抱怨......)

    【讨论】:

    • 你也可以使用reformulate(restring1, response = 'someDV')
    • 这必须是最快满意答案的新记录。现在我学会了一种方便的公式构建新方法!非常感谢你们俩。
    猜你喜欢
    • 2012-11-08
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多