繁体   English   中英

如何在 R 中创建具有各种变量的回归线

[英]How do I create a regression line with various variables in R

我已经创建了实际的回归代码,但我试图将回归线和预测线绘制到图上,但我似乎无法弄清楚。

m1 <- lm(variable1 ~ 2 + 3 + 4 + 5 + 6 + 7 + 8, data = prog)
summary(m1)

然后我想在hyp.data的基础上创建绘图,但我仍然有点迷茫。

考虑两个(不是 7 个!)预测变量; 一个是numeric ,另一个是分类的(即一个factor )。

# Simulate data
set.seed(2017);
x1 <- 1:10;
x2 <- as.factor(sample(c("treated", "not_treated"), 10, replace = TRUE));
df <- cbind.data.frame(
    y = 2 * x1 + as.numeric(x2) - 1 + rnorm(10),
    x1 = x1,
    x2 = x2);

在这种情况下,您可以执行以下操作:

# Fit the linear model    
m1 <- lm(y ~ x1 + x2, data = df);

# Get predictions
df$pred <- predict(m1);

# Plot data    
library(ggplot2);
ggplot(df, aes(x = x1, y = y)) +
    geom_point() +
    facet_wrap(~ x2, scales = "free") +
    geom_line(aes(x = x1, y = pred), col = "red");

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM