将字符串传递给 lme/lmer 的 'contrasts' 参数

Passing strings into 'contrasts' argument of lme/lmer

我正在编写 return 纵向混合效应模型输出的子程序。我希望能够将变量列表中的元素作为结果和预测变量传递到 lme/lmer 中。我还希望能够在这些混合效果模型中指定对比,但是我无法让 contrasts() 参数将字符串识别为相同 [= 中模型规范中引用的变量名称18=]呼唤。

这是一些玩具数据,

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() 函数的变量?

您应该能够在对比列表中使用 setNames() 将全名应用于列表:

# Using a %>% pipe so need to load magrittr
library(magrittr)

mod2R <- lme(reformulate(paste0(g,"*",t), response = "score"), 
             random = ~1|id, 
             data = df, 
             contrasts = list(g = contr.treatment(2), t = contr.treatment(4)) %>%
                 setNames(c(g, t))
             )