首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何预测和绘制非线性变化的斜率?

如何预测和绘制非线性变化的斜率?
EN

Stack Overflow用户
提问于 2014-04-27 23:00:18
回答 1查看 2K关注 0票数 4

我的目标是使用R中的lmerglmer包的lme4函数,从一个可变截距、变斜率的多级模型中计算预测值。为了使这个具体和清晰,我在这里给出一个带有“mtcar”数据集的玩具示例:

下面是我通常如何从一个变化的截距,变斜率的多级模型中创建预测值(这段代码应该工作得很好):

代码语言:javascript
复制
# 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”数据集的绊脚石:

代码语言:javascript
复制
# 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中拟合非线性变截距、变斜率多级模型时如何创建和绘制预测值有任何想法吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-27 23:18:19

问题是,当您将expand.gridwtwt^2同时使用时,您将创建wtwt^2的所有可能组合。对代码的这种修改是有效的:

代码语言:javascript
复制
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")
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23330097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档