【问题标题】:How do I create a regression line with various variables in R如何在 R 中创建具有各种变量的回归线
【发布时间】:2018-08-07 18:19:50
【问题描述】:

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

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

然后我想在hyp.data的基础上创建情节,但我还是有点迷茫。

【问题讨论】:

  • 一般来说,在基础 R 绘图中,您可以在绘制数据后简单地执行 abline(m1)。但是,您打算如何将数据可视化为 8 个维度?
  • 是的,我很确定我也应该创建一条带有预测的线。我应该使用lm(outcome variable ~ treatment+ counfounders1through8),然后从中创建 2 行。
  • 你没有回答我的问题。 you 如何计划用 8 维预测绘制一条线?看看下面一个更简单的例子。

标签: r plot regression prediction


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-11-05
    • 1970-01-01
    • 2020-05-20
    • 2018-03-18
    • 2018-07-13
    • 2021-11-28
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多