【发布时间】:2018-10-09 23:51:53
【问题描述】:
我正在编写一个子程序来返回纵向混合效应模型的输出。我希望能够将变量列表中的元素作为结果和预测变量传递到lme/lmer。我还希望能够在这些混合效果模型中指定对比,但是我无法让 contrasts() 参数将字符串识别为同一 lme/lme4 调用中模型规范中引用的变量名称.
这是一些玩具数据,
set.seed(345)
A0 <- rnorm(4,2,.5)
B0 <- rnorm(4,2+3,.5)
A1 <- rnorm(4,6,.5)
B1 <- rnorm(4,6+2,.5)
A2 <- rnorm(4,10,.5)
B2 <- rnorm(4,10+1,.5)
A3 <- rnorm(4,14,.5)
B3 <- rnorm(4,14+0,.5)
score <- c(A0,B0,A1,B1,A2,B2,A3,B3)
id <- rep(1:8,times = 4, length = 32)
time <- factor(rep(0:3, each = 8, length = 32))
group <- factor(rep(c("A","B"), times =2, each = 4, length = 32))
df <- data.frame(id = id, group = group, time = time, score = score)
现在对lme 的以下调用工作正常,并指定了对比(我知道这些是默认设置,所以这都是纯粹的教学)。
mod <- lme(score ~ group*time, random = ~1|id, data = df, contrasts = list(group = contr.treatment(2), time = contr.treatment(4)))
以下方法也有效,使用 reformulate() 函数将字符串作为变量名传递到 lme。
t <- "time"
g <- "group"
dv <- "score"
mod1R <- lme(reformulate(paste0(g,"*",t), response = "score"), random = ~1|id, data = df)
但是如果我想指定对比,就像在第一个示例中一样,它不起作用
mod2R <- lme(reformulate(paste0(g,"*",t), response = "score"), random = ~1|id, data = df, contrasts = list(g = contr.treatment(2), t = contr.treatment(4)))
# Error in `contrasts<-`(`*tmp*`, value = contrasts[[i]]) : contrasts apply only to factors
如何让lme 识别contrasts 参数中指定的字符串引用传递给reformulate() 函数的变量?
【问题讨论】: