p <- nlme::Oxboys %>% ggplot(aes(age,height,group=Subject))+geom_line()

1. 建模
model <- lme(height~age,data = nlme::Oxboys,random = ~ 1 + age|Subject)
2. 如何判断模型好坏
2.1 自建测试数据集,根据模型用预测的x~y关系绘图,在图上比较
age_grid <- seq(-1,1,length=10)
sample <- unique(nlme::Oxboys$Subject)
preds <- expand.grid(age=age_grid,Subject=sample)
expand.grid()扩充为数据框
先对第二列排序,再对第一列排序
preds$height <- predict(model,preds)
predict()提供模型和input,做预测,并返回一列y值;
input可以是数据框,包含与建模时同名(age)的x变量;
input可选,如果不提供,则用建模时的x变量。
p+geom_line(data=preds,color="lightblue")
运用到的图层语法:在不同的图层改变图形属性和数据集

看上去还可以?!
2.2 观察残差
Oxboys$fitted <- predict(model)
Oxboys$resid <- with(Oxboys, fitted - height)
p %+% Oxboys+aes(y=resid)+geom_smooth(aes(group=1))
#%+%表示更新,更新了数据集、图形属性的映射、几何对象

图形反映出残差跟x即age有明显的关系(先增后减),因此该模型不合适。正常情况下,应无规律地分散在y=0的两侧。
3. 改善模型
model2 <- update(model, height ~ age + I(age ^ 2))
Oxboys$fitted2 <- predict(model2)
Oxboys$resid2 <- with(Oxboys, fitted2 - height)
p %+% Oxboys+aes(y=resid2)+geom_smooth(aes(group=1))

网友评论