我正在编写一个子例程来返回纵向混合效果模型的输出。我希望能够将变量列表中的元素作为结果变量和预测变量传递到lme/lmer
中。我还希望能够在这些混合效果模型中指定对比度,但是我很难让contrasts()
参数将字符串识别为同一{{中的模型规范中引用的变量名1}}通话。
这里有一些玩具数据,
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)))
函数将字符串作为变量名传递到lme
中。
reformulate()
但是,如果我想指定对比度,就像第一个示例一样,那是行不通的
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
函数的变量?
答案 0 :(得分:2)
您应该能够在对比列表上使用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))
)