【问题标题】:Linear Regression with a known fixed intercept in RR中具有已知固定截距的线性回归
【发布时间】:2011-11-12 02:09:03
【问题描述】:

我想使用 R 中的 lm() 函数计算线性回归。此外,我想获得回归的斜率,其中我明确地将截距赋予 lm()

我在互联网上找到了一个示例,并尝试阅读 R 帮助“?lm”(不幸的是我无法理解它),但没有成功。谁能告诉我我的错误在哪里?

lin <- data.frame(x = c(0:6), y = c(0.3, 0.1, 0.9, 3.1, 5, 4.9, 6.2))
plot (lin$x, lin$y)

regImp = lm(formula = lin$x ~ lin$y)
abline(regImp, col="blue")

# Does not work:
# Use 1 as intercept
explicitIntercept = rep(1, length(lin$x))
regExp = lm(formula = lin$x ~ lin$y + explicitIntercept)
abline(regExp, col="green")

感谢您的帮助。

【问题讨论】:

    标签: r regression linear-regression lm


    【解决方案1】:

    您可以从回归中减去显式截距,然后拟合无截距模型:

    > intercept <- 1.0
    > fit <- lm(I(x - intercept) ~ 0 + y, lin)
    > summary(fit)
    

    0 + 抑制了 lm 对截距的拟合。

    编辑要绘制拟合,请使用

    > abline(intercept, coef(fit))
    

    附:模型中的变量看起来是错误的:它通常是 y ~ x,而不是 x ~ y(即回归量应该在左边,回归量在右边)。

    【讨论】:

    • I(x - 1.0)~ y-1 也抑制了截距的拟合。
    • @Joris Meys:是的。我相信这两种方式是同义的。我选择了另一种方式,以避免有两个 -1 术语并且不得不解释哪个是哪个。
    • 但是当我绘制回归曲线 abline(regExp, col="green") 时,它没有通过 1。我还没有弄清楚如何提取斜率(和/或截距)来自 lm 输出。对于我来说,您似乎总是必须知道值在 coef 数组中的位置,而不是提取(并希望位置正确)。那么,以下代码是绘制正确回归曲线的“黄金方式”吗? abline(b=coef(regExp)[1], a= explicitIntercept, col="green")
    • @Sven: abline(1.0, coef(fit)) 绘制拟合图(这里,1.0 是显式截距)。我已更新答案以包含此内容。
    • 另见offset 参数。
    【解决方案2】:

    我看到您已经接受了使用 I() 的解决方案。我原以为基于 offset() 的解决方案会更明显,但口味各不相同,在完成 offset 解决方案后,我可以体会到 I() 解决方案的经济性:

    with(lin, plot(y,x) )
    lm_shift_up <- lm(x ~ y +0 + 
                           offset(rep(1, nrow(lin))), 
                 data=lin)
    abline(1,coef(lm_shift_up))
    

    【讨论】:

      【解决方案3】:

      我同时使用了偏移量和 I()。我还发现偏移更容易使用(如 BondedDust),因为您可以设置截距。

      假设截距为 10。

      plot (lin$x, lin$y) fit <-lm(lin$y~0 +lin$x,offset=rep(10,length(lin$x))) abline(fit,col="blue")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-27
        • 2022-01-09
        • 2018-01-02
        • 2015-10-28
        • 2018-06-11
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        相关资源
        最近更新 更多