我在尝试在函数中嵌入lmer
时遇到了问题。以下是使用lexdec
数据的可重现示例。如果我直接在数据框上运行lmer
,则没有问题。例如,假设我想看看词汇决策任务中的阅读时间是否与试验的函数不同。有两种类型的单词刺激,“动物”(例如“狗”)和“植物”(例如“樱桃”)。我可以为动物词计算混合效应模型:
library(languageR) #load lexdec data
library(lme4) #load lmer()
s <- summary(lmer(RT ~ Trial + (1|Subject) + (1|Word), data = lexdec[lexdec$Class== "animal", ]))
s #this works well
但是,如果我将lmer模型嵌入到函数中(比如不为每个级别类型输入相同的命令),我会收到一条错误消息。 你知道为什么吗?非常感谢任何建议!
#lmer() is now embedded in a function
compute.lmer <- function(df,class) {
m <- lmer(RT ~ Trial + (1|Subject) + (1|Word),data = df[df$Class== class, ])
m <- summary(m)
return(m)
}
#Now I can use this function to iterate over the 2 levels of the **Class** factor
for (c in levels(lexdec$Class)){
s <- compute.lmer(lexdec,c)
print(c)
print(s)
}
#But this gives an error message
Error in `colnames<-`(`*tmp*`, value = c("Estimate", "Std. Error", "df", :
length of 'dimnames' [2] not equal to array extent
答案 0 :(得分:2)
我不知道问题是什么,你的代码运行得很好。 (您的软件包是否是最新的?您运行的是什么R版本?您是否已清理工作区并从头开始尝试代码?)
尽管如此,这是plyr::dlply
的一个很好的用例。我会这样做:
library(languageR)
library(lme4)
library(plyr)
stats <- dlply(lexdec,
.variables = c("Class"),
.fun=function(x) return(summary(lmer(RT ~ Trial + (1 | Subject) +
(1 | Word), data = x))))
names(stats) <- levels(lexdec$Class)
然后产生
> stats[["plant"]]
Linear mixed model fit by REML ['lmerMod']
Formula: RT ~ Trial + (1 | Subject) + (1 | Word)
Data: x
REML criterion at convergence: -389.5
Scaled residuals:
Min 1Q Median 3Q Max
-2.2647 -0.6082 -0.1155 0.4502 6.0593
Random effects:
Groups Name Variance Std.Dev.
Word (Intercept) 0.003718 0.06097
Subject (Intercept) 0.023293 0.15262
Residual 0.028697 0.16940
Number of obs: 735, groups: Word, 35; Subject, 21
Fixed effects:
Estimate Std. Error t value
(Intercept) 6.3999245 0.0382700 167.23
Trial -0.0001702 0.0001357 -1.25
Correlation of Fixed Effects:
(Intr)
Trial -0.379
当我运行你的代码(复制和粘贴而不做修改)时,我得到了类似的输出。除了Data:
行之外,它是相同的。
stats = list()
compute.lmer <- function(df,class) {
m <- lmer(RT ~ Trial + (1|Subject) + (1|Word),data = df[df$Class== class, ])
m <- summary(m)
return(m)
}
for (c in levels(lexdec$Class)){
s <- compute.lmer(lexdec,c)
stats[[c]] <- s
}
> stats[["plant"]]
Linear mixed model fit by REML ['lmerMod']
Formula: RT ~ Trial + (1 | Subject) + (1 | Word)
Data: df[df$Class == class, ]
REML criterion at convergence: -389.5
Scaled residuals:
Min 1Q Median 3Q Max
-2.2647 -0.6082 -0.1155 0.4502 6.0593
Random effects:
Groups Name Variance Std.Dev.
Word (Intercept) 0.003718 0.06097
Subject (Intercept) 0.023293 0.15262
Residual 0.028697 0.16940
Number of obs: 735, groups: Word, 35; Subject, 21
Fixed effects:
Estimate Std. Error t value
(Intercept) 6.3999245 0.0382700 167.23
Trial -0.0001702 0.0001357 -1.25
Correlation of Fixed Effects:
(Intr)
Trial -0.379