我的目标是使用R中的lmer和glmer包的lme4函数,从一个可变截距、变斜率的多级模型中计算预测值。为了使这个具体和清晰,我在这里给出一个带有“mtcar”数据集的玩具示例:
下面是我通常如何从一个变化的截距,变斜率的多级模型中创建预测值(这段代码应该工作得很好):
# loading in-built cars dataset
data(mtcars)
# the "gear" column will be the group-level factor, so we'll have cars nested
# within "gear" type
mtcars$gear <- as.factor(mtcars$gear)
# fitting varying-slope, varying-intercept model
m <- lmer(mpg ~ 1 + wt + hp + (1 + wt|gear), data=mtcars)
# creating the prediction frame
newdata <- with(mtcars, expand.grid(wt=unique(wt),
gear=unique(gear),
hp=mean(hp)))
# calculating predictions
newdata$pred <- predict(m, newdata, re.form=~(1 + wt|gear))
# quick ggplot2 graph
p <- ggplot(newdata, aes(x=wt, y=pred, colour=gear))
p + geom_line() + ggtitle("Varying Slopes")

上面的R代码应该可以工作,但是如果我想从一个非线性的变化截距,变斜率中创建和绘制预测,那么它显然失败了。为了简单和可重复性,下面是使用“mtcar”数据集的绊脚石:
# key question: how to create predictions if I want to examine a non-linear
# varying slope?
# creating a squared term for a non-linear relationship
# NB: usually I use the `poly` function
mtcars$wtsq <- (mtcars$wt)^2
# fitting varying-slope, varying-intercept model with a non-linear trend
m <- lmer(mpg ~ 1 + wt + wtsq + hp + (1 + wt + wtsq|gear), data=mtcars)
# creating the prediction frame
newdata <- with(mtcars, expand.grid(wt=unique(wt),
wtsq=unique(wtsq),
gear=unique(gear),
hp=mean(hp)))
# calculating predictions
newdata$pred <- predict(m, newdata, re.form=~(1 + wt + wtsq|gear))
# quick ggplot2 graph
# clearly not correct (see the graph below)
p <- ggplot(newdata, aes(x=wt, y=pred, colour=gear))
p + geom_line() + ggtitle("Varying Slopes")

显然,预测框架没有正确设置。对于如何在R中拟合非线性变截距、变斜率多级模型时如何创建和绘制预测值有任何想法吗?谢谢!
发布于 2014-04-27 23:18:19
问题是,当您将expand.grid与wt和wt^2同时使用时,您将创建wt和wt^2的所有可能组合。对代码的这种修改是有效的:
newdata <- with(mtcars, expand.grid(wt=unique(wt),
gear=unique(gear),
hp=mean(hp)))
newdata$wtsq <- newdata$wt^2
newdata$pred <- predict(m, newdata)
p <- ggplot(newdata, aes(x=wt, y=pred, colour=gear, group=gear))
p + geom_line() + ggtitle("Varying Slopes")https://stackoverflow.com/questions/23330097
复制相似问题