0
我試圖在分組數據上運行多個混合效果模型。下面是代碼:分組後運行多個模型並保存爲數據框中的列
library(dplyr)
library(lme4)
dat.tx.a <- mvrnorm(n=250, mu=c(30, 20, 28),
Sigma=matrix(c(25.0, 17.5, 12.3,
17.5, 25.0, 17.5,
12.3, 17.5, 25.0), nrow=3, byrow=TRUE))
dat.tx.b <- mvrnorm(n=250, mu=c(30, 20, 22),
Sigma=matrix(c(25.0, 17.5, 12.3,
17.5, 25.0, 17.5,
12.3, 17.5, 25.0), nrow=3, byrow=TRUE))
dat <- data.frame(rbind(dat.tx.a, dat.tx.b))
names(dat) = c("measure.1", "measure.2", "measure.3")
dat <- data.frame(subject.id=factor(1:500), tx=rep(c("A", "B"), each=250), dat)
rm(dat.tx.a, dat.tx.b)
dat <- reshape(dat, varying=c("measure.1", "measure.2", "measure.3"),
idvar="subject.id", direction="long")
df.model<-dat %>%
group_by(tx) %>%
do (model1=lmer(measure~(1|subject.id), data=.)) %>%
do (model2=lmer(measure~time+(1|subject.id), data=.))
以下是錯誤消息:如果我刪除運行MODEL2行
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class "structure("lmerMod", package = "lme4")" to a data.frame
代碼工作。數據框似乎只接受一列作爲模型列表?非常感謝。
由於您正在使用管道('%>%'),您實際上在做的是將'do(model1 ...)'的輸出傳遞給語句'do(model2 ...)',當然不是你打算做的事情。相反,你可以編寫一個適合兩種模型的函數並返回一個列表。 –