【发布时间】:2019-04-18 21:09:20
【问题描述】:
我使用lme4 包安装了一个混合模型。在拟合模型之前,我使用 scale() 函数转换了自变量。我现在想使用predict() 在图表上显示我的结果,因此我需要将预测数据恢复到原始比例。我该怎么做?
简化示例:
database <- mtcars
# Scale data
database$wt <- scale(mtcars$wt)
database$am <- scale(mtcars$am)
# Make model
model.1 <- glmer(vs ~ scale(wt) + scale(am) + (1|carb), database, family = binomial, na.action = "na.fail")
# make new data frame with all values set to their mean
xweight <- as.data.frame(lapply(lapply(database[, -1], mean), rep, 100))
# make new values for wt
xweight$wt <- (wt = seq(min(database$wt), max(database$wt), length = 100))
# predict from new values
a <- predict(model.1, newdata = xweight, type="response", re.form=NA)
# returns scaled prediction
我尝试使用this example 对预测进行反向转换:
# save scale and center values
scaleList <- list(scale = attr(database$wt, "scaled:scale"),
center = attr(database$wt, "scaled:center"))
# back-transform predictions
a.unscaled <- a * scaleList$scale + scaleList$center
# Make model with unscaled data to compare
un.model.1 <- glmer(vs ~ wt + am + (1|carb), mtcars, family = binomial, na.action = "na.fail")
# make new data frame with all values set to their mean
un.xweight <- as.data.frame(lapply(lapply(mtcars[, -1], mean), rep, 100))
# make new values for wt
un.xweight$wt <- (wt = seq(min(mtcars$wt), max(mtcars$wt), length = 100))
# predict from new values
b <- predict(un.model.1, newdata = xweight, type="response", re.form=NA)
all.equal(a.unscaled,b)
# [1] "Mean relative difference: 0.7223061"
这不起作用 - 应该没有任何区别。 我做错了什么?
我也查看了许多类似的问题,但没有设法将任何问题应用于我的案例(How to unscale the coefficients from an lmer()-model fitted with a scaled response、unscale and uncenter glmer parameters、Scale back linear regression coefficients in R from scaled and centered data、https://stats.stackexchange.com/questions/302448/back-transform-mixed-effects-models-regression-coefficients-for-fixed-effects-f)。
【问题讨论】:
标签: r regression scale lme4