Linear Regression with a known fixed intercept in R

北战南征 提交于 2019-11-26 15:20:37

问题


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().

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")

Thanls for your help.


回答1:


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)

The 0 + suppresses the fitting of the intercept by lm.

edit To plot the fit, use

> abline(intercept, coef(fit))

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).




回答2:


I see that you have accepted a solution using I(). I had thought that an offset() based solution would have been more obvious, but tastes vary and after working through the offset solution I can appreciate the economy of the I() solution:

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 have used both offset and I(). I also find offset easier to work with (like BondedDust) since you can set your intercept.

Assuming Intercept is 10.

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



来源:https://stackoverflow.com/questions/7333203/linear-regression-with-a-known-fixed-intercept-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!