绘制具有二项式误差的广义混合效应模型

机器算法验证 r 回归 数据可视化 二项分布 lme4-nlme
2022-03-22 22:20:30

使用predict函数绘制glm二项式模型相当简单。我无法为glmer模型创建类似的图;预测不起作用:

id    <- factor(rep(1:20, 3))
age   <- rep(sample(20:50, 20, replace=T), 3)
age   <- age + c(rep(0, 20), rep(3, 20), rep(6, 20))
score <- rbinom(60, 15, 1-age/max(age))
dfx   <- data.frame(id, age, score)

library(lme4)
glmerb  <- glmer(cbind(score, 15-score) ~ age + (1|id), dfx, family=binomial)
ndf     <- expand.grid(age=10:60) #for extensibility, usually also have factors
ndf$fit <- predict(glmerb, ndf, type="response")
*Error in UseMethod("predict") : no applicable method for 'predict' applied to an object of class "mer"*
  1. 如何制作所需的情节?
  2. 当我在做的时候,还有什么其他的情节对这种模型有用,无论是诊断、演示还是华丽目的?
3个回答

看看 ez 包,尤其是 ezPredict。

附言。如果您想使用“to_predict”参数,则需要开发版本,请参阅此处的说明:https ://github.com/mike-lawrence/ez

问题是 中的merRlmeretc 命令lme4都产生mer对象,并且这些与某些“正常” R 命令不兼容。

您可以通过使用fitted但修改您的代码来解决问题

ndf$fit <- fitted(glmerb, ndf, type="response")

给了我错误

Error in `$<-.data.frame`(`*tmp*`, "fit", value = c(0.213527879025905,  : 
replacement has 60 rows, data has 51

但这有效:

> fit <- fitted(glmerb, ndf, type="response")
> str(fit)
num [1:60] 0.214 0.282 0.335 0.154 0.335 ...

那是你所追求的吗?

为了绘制固定效果的曲线,我通常使用如下代码:

model.coefs <- fixef(model)
curve( invlogit( cbind(1, x) %*% model.coefs ), add=TRUE )

请注意,这invlogit是在arm包中。