我想使用 R 中的 lm() 函数计算线性回归。此外,我想获得回归的斜率,其中我明确地将截距赋予 lm()
。
我在互联网上找到了一个例子,我尝试阅读R-help“?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")
感谢您的帮助。
最佳答案
您可以从回归中减去显式截距,然后拟合无截距模型:
> intercept <- 1.0
> fit <- lm(I(x - intercept) ~ 0 + y, lin)
> summary(fit)
0 +
通过 lm
抑制截距拟合。
编辑要绘制拟合图,请使用
> abline(intercept, coef(fit))
附注模型中的变量看起来是错误的:通常是 y ~ x
,而不是 x ~ y
(即回归变量应位于左侧,回归变量应位于左侧)右边)。
关于r - R 中已知固定截距的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7333203/