为了帮助填充R标签,我发布了一些我经常从学生处收到的问题。多年来,我已经为自己找到了自己的答案,但也许有更好的方法可以解决我不知道的问题。从线性模型中绘制交互效果的最佳方法
的问题:我刚跑了回归连续y
和x
但是因素f
(其中levels(f)
产生c("level1","level2")
)
thelm <- lm(y~x*f,data=thedata)
现在我想通过x
按组划分绘制的y
的预测值由f
定义。我得到的所有情节都很丑陋,并显示太多线条。
我的回答:尝试predict()
函数。
##restrict prediction to the valid data
##from the model by using thelm$model rather than thedata
thedata$yhat <- predict(thelm,
newdata=expand.grid(x=range(thelm$model$x),
f=levels(thelm$model$f)))
plot(yhat~x,data=thethedata,subset=f=="level1")
lines(yhat~x,data=thedata,subset=f=="level2")
还有其他的想法是:(1)更容易理解新手和/或(2)更好从其他角度?
请注意,'ggplot2'有一个函数'fortify.lm',它补充了一些线性模型拟合统计数据 – mnel 2012-10-22 22:57:26