从lme拟合中提取预测带

时间:2013-01-16 12:45:46

标签: r prediction confidence-interval mixed-models

我有以下模型

x  <- rep(seq(0, 100, by=1), 10)
y  <- 15 + 2*rnorm(1010, 10, 4)*x + rnorm(1010, 20, 100)
id <- NULL
for(i in 1:10){ id <- c(id, rep(i,101)) }
dtfr <- data.frame(x=x,y=y, id=id)
library(nlme)
with(dtfr, summary(     lme(y~x, random=~1+x|id, na.action=na.omit)))
model.mx <- with(dtfr, (lme(y~x, random=~1+x|id, na.action=na.omit)))
pd       <- predict( model.mx, newdata=data.frame(x=0:100), level=0)
with(dtfr, plot(x, y))
lines(0:100, predict(model.mx, newdata=data.frame(x=0:100), level=0), col="darkred", lwd=7)

enter image description here

使用predictlevel=0我可以绘制平均人口响应。如何从nlme对象中提取并绘制整个群体的95%置信区间/预测带?

2 个答案:

答案 0 :(得分:23)

警告:在执行此操作之前,请先阅读this thread on r-sig-mixed models。解释结果预测带时要非常小心。

r-sig-mixed models FAQ调整到您的示例:

set.seed(42)
x <- rep(0:100,10)
y <- 15 + 2*rnorm(1010,10,4)*x + rnorm(1010,20,100)
id<-rep(1:10,each=101)

dtfr <- data.frame(x=x ,y=y, id=id)

library(nlme)

model.mx <- lme(y~x,random=~1+x|id,data=dtfr)

#create data.frame with new values for predictors
#more than one predictor is possible
new.dat <- data.frame(x=0:100)
#predict response
new.dat$pred <- predict(model.mx, newdata=new.dat,level=0)

#create design matrix
Designmat <- model.matrix(eval(eval(model.mx$call$fixed)[-2]), new.dat[-ncol(new.dat)])

#compute standard error for predictions
predvar <- diag(Designmat %*% model.mx$varFix %*% t(Designmat))
new.dat$SE <- sqrt(predvar) 
new.dat$SE2 <- sqrt(predvar+model.mx$sigma^2)

library(ggplot2) 
p1 <- ggplot(new.dat,aes(x=x,y=pred)) + 
geom_line() +
geom_ribbon(aes(ymin=pred-2*SE2,ymax=pred+2*SE2),alpha=0.2,fill="red") +
geom_ribbon(aes(ymin=pred-2*SE,ymax=pred+2*SE),alpha=0.2,fill="blue") +
geom_point(data=dtfr,aes(x=x,y=y)) +
scale_y_continuous("y")
p1

plot

答案 1 :(得分:1)

很抱歉回到这么老的话题,但这可能在这里发表评论:

  

如果某些软件包可以提供此功能,那就很好

当您使用type = "re"时,此功能包含在ggeffects-package中(然后将包括随机效应差异,而不仅是残余差异 >,但在此特定示例中相同)。

library(nlme)
library(ggeffects)

x  <- rep(seq(0, 100, by = 1), 10)
y  <- 15 + 2 * rnorm(1010, 10, 4) * x + rnorm(1010, 20, 100)
id <- NULL
for (i in 1:10) {
  id <- c(id, rep(i, 101))
}
dtfr <- data.frame(x = x, y = y, id = id)
m <- lme(y ~ x,
         random =  ~ 1 + x | id,
         data = dtfr,
         na.action = na.omit)

ggpredict(m, "x") %>% plot(rawdata = T, dot.alpha = 0.2)

ggpredict(m, "x", type = "re") %>% plot(rawdata = T, dot.alpha = 0.2)

reprex package(v0.3.0)于2019-06-18创建