将字符串传递给lme/lmer的"contrasts"参数 [英] Passing strings into 'contrasts' argument of lme/lmer
问题描述
我正在编写一个子例程来返回纵向混合效果模型的输出.我希望能够将变量列表中的元素作为结果和预测变量传递到 lme/lmer
中.我还希望能够在这些混合效果模型中指定对比度,但是我很难获取 contrasts()
参数以将字符串识别为模型规范中引用的变量名称在同一 lme/lme4
调用中.
I am writing a sub-routine to return output of longitudinal mixed-effects models. I want to be able to pass elements from lists of variables into lme/lmer
as the outcome and predictor variables. I would also like to be able to specify contrasts within these mixed-effects models, however I am having trouble with getting the contrasts()
argument to recognise the strings as the variable names referred to in the model specification within the same lme/lme4
call.
这里有一些玩具数据,
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
的调用可以正常工作,并指定了对比(我知道这些是默认的,所以这纯粹是教学目的).
Now the following call to lme
works just fine, with contrasts specified (I know these are the default so this is all purely pedagogical).
mod <- lme(score ~ group*time, random = ~1|id, data = df, contrasts = list(group = contr.treatment(2), time = contr.treatment(4)))
以下内容也可以使用 reformulate()
函数将字符串作为变量名传递到 lme
中.
The following also works, passing strings as variable names into lme
using the reformulate()
function.
t <- "time"
g <- "group"
dv <- "score"
mod1R <- lme(reformulate(paste0(g,"*",t), response = "score"), random = ~1|id, data = df)
但是,如果我想指定对比度,如第一个示例中所示,那是行不通的
But if I want to specify contrasts, like in the first example, it doesn't work
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()
的变量功能?
How do I get lme
to recognise that the strings specified to in the contrasts
argument refer to the variables passed into the reformulate()
function?
推荐答案
您应该能够在对比列表上使用 setNames()
将全名应用于列表:
You should be able to use setNames()
on the list of contrasts to apply the full names to the list:
# 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))
)
这篇关于将字符串传递给lme/lmer的"contrasts"参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!