R中具有已知固定截距的线性回归 [英] Linear Regression with a known fixed intercept in R
问题描述
我想使用R中的lm()函数来计算线性回归.此外,我想获得回归的斜率,在此我将截距明确地赋予lm()
.
I want to calculate a linear regression using the lm() function in R. Additionally I want to get the slope of a regression, where I explicitly give the intercept to lm()
.
我在互联网上找到一个示例,尝试读取R帮助?lm"(不幸的是我听不懂),但没有成功.谁能告诉我我的错误在哪里?
I found an example on the internet and I tried to read the R-help "?lm" (unfortunately I'm not able to understand it), but I did not succeed. Can anyone tell me where my mistake is?
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")
感谢您的帮助.
推荐答案
您可以从回归中减去显式截距,然后拟合无截距模型:
You could subtract the explicit intercept from the regressand and then fit the intercept-free model:
> intercept <- 1.0
> fit <- lm(I(x - intercept) ~ 0 + y, lin)
> summary(fit)
0 +
抑制lm
对截距的拟合.
编辑,要绘制拟合,请使用
edit To plot the fit, use
> abline(intercept, coef(fit))
P.S.模型中的变量看起来是错误的:通常是y ~ x
,而不是x ~ y
(即,回归变量应在左侧,而回归变量应在右侧).
P.S. The variables in your model look the wrong way round: it's usually y ~ x
, not x ~ y
(i.e. the regressand should go on the left and the regressor(s) on the right).
这篇关于R中具有已知固定截距的线性回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!