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.
The mathematical formula of the linear regression can be written as y = b0 + b1*x + e , where: b0 and b1 are known as the regression beta coefficients or parameters: b0 is the intercept of the regression line; that is the predicted value when x = 0 . b1 is the slope of the regression line.
Regression through the origin is when you force the intercept of a regression model to equal zero. It's also known as fitting a model without an intercept (e.g., the intercept-free linear model y=bx is equivalent to the model y=a+bx with a=0).
The intercept (often labeled as constant) is the point where the function crosses the y-axis. In some analysis, the regression model only becomes significant when we remove the intercept, and the regression line reduces to Y = bX + error.
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).
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With