R中的偏回归图

R中的偏回归图,r,plot,ggplot2,regression,R,Plot,Ggplot2,Regression,我对R很陌生,我很想得到一些帮助,为一个研究项目创建一个偏回归图 这是我的完整模型: model2 <- lm(scenarios_anger ~ 1 + scenarios + age + female + politics + relg + spirit, data=data) 问题是我似乎无法将剩余值插入ggplot函数来创建散点图。我试过这个命令: ggplot(data, aes(x = resid.model2b, y = resid.model1)) + geom_poin

我对R很陌生,我很想得到一些帮助,为一个研究项目创建一个偏回归图

这是我的完整模型:

model2 <- lm(scenarios_anger ~ 1 + scenarios + age + female + politics + relg + spirit, data=data)
问题是我似乎无法将剩余值插入ggplot函数来创建散点图。我试过这个命令:

ggplot(data, aes(x = resid.model2b, y = resid.model1)) + geom_point(na.rm=T)
但我收到的错误消息是:
error:美学必须是长度1或与数据(786)相同:x,y


我想知道这是否是因为我的残差不是ggplot函数的正确类别?我如何解决这个问题?或者是否有其他方法来创建我的偏回归图?

这里的问题是,要在图中使用的残差是新创建的对象,不在数据框
数据中。因此,当您发出
ggplot
命令时,它将查找不存在的剩余变量。您应该将残差变量添加回数据框
data
,或者使用这些残差创建一个新的数据框,用于绘图。对于后一种方法,您可以执行如下操作:

#Create the residuals (same as in your question)
model1 <- lm(scenarios_anger ~ 1 + age + female + politics + rely + spirit, data=data);
resid.model1 <- residuals(model1);
model2b <- lm(scenarios ~ 1 + age + female + politics + relg + spirit, data=data);
resid.model2b <- residuals(model2b);

#Create new data frame containing those residuals
NEWDF <- data.frame(RES1 = resid.model1, RES2b = resid.model2b);

#Now generate your plot using this NEWDF as your data
library(ggplot2);
ggplot(data = NEWDF, aes(x = resid.model2b, y = resid.model1)) + geom_point(na.rm=T);
#创建残差(与您的问题相同)

model1 ggplot仅将data.frame作为其
data
参数,并且您在
aes
中指定的美学应该是该data.frame中的裸列名。在这里,您需要类似于
ggplot(data.frame(m1=残差(model1),m2b=残差(model2b)),aes(x=m1,y=m2b))+geom_point()
我的建议是在原始
model1
data.frame中添加所有残差和其他变量。这样,使用给定的建模和ggplot2的R函数对其中任何一个进行绘图或建模都是“开箱即用”的。@RomanLuštrik感谢您的建议
broom::augment
是向data.frame中添加残差(以及拟合值等)的一种非常快速的方法,如果您愿意的话。
#Create the residuals (same as in your question)
model1 <- lm(scenarios_anger ~ 1 + age + female + politics + rely + spirit, data=data);
resid.model1 <- residuals(model1);
model2b <- lm(scenarios ~ 1 + age + female + politics + relg + spirit, data=data);
resid.model2b <- residuals(model2b);

#Create new data frame containing those residuals
NEWDF <- data.frame(RES1 = resid.model1, RES2b = resid.model2b);

#Now generate your plot using this NEWDF as your data
library(ggplot2);
ggplot(data = NEWDF, aes(x = resid.model2b, y = resid.model1)) + geom_point(na.rm=T);