gpt4 book ai didi

r - 从线性模型绘制交互效果的最佳方法

转载 作者:行者123 更新时间:2023-12-03 20:22:08 25 4
gpt4 key购买 nike

为了帮助在此处填充 R 标签,我发布了一些我经常从学生那里收到的问题。这些年来,我已经对这些问题提出了自己的答案,但也许还有更好的方法我不知道。

问题:我刚刚使用连续 y 进行回归和 x但因素 f (其中 levels(f) 产生 c("level1","level2") )

 thelm <- lm(y~x*f,data=thedata)

现在我想绘制 y 的预测值通过 xf 定义的组划分.我得到的所有情节都很丑陋,而且线条太多。

我的回答:试试 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)从其他角度更好?

最佳答案

效果包有很好的绘图方法来可视化回归的预测值。

thedata<-data.frame(x=rnorm(20),f=rep(c("level1","level2"),10))
thedata$y<-rnorm(20,,3)+thedata$x*(as.numeric(thedata$f)-1)

library(effects)
model.lm <- lm(formula=y ~ x*f,data=thedata)
plot(effect(term="x:f",mod=model.lm,default.levels=20),multiline=TRUE)

关于r - 从线性模型绘制交互效果的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1395147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com