如何在R

时间:2018-02-28 00:01:31

标签: r plot regression prediction

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

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

然后我想在hyp.data的基础上创建情节,但我仍然有点失落。

1 个答案:

答案 0 :(得分:0)

考虑两个(不是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");

enter image description here

相关问题