4

I'm doing a least-square regression on some data, the function has the form

y ~ a + b*x

and I want the regression line to pass through a specific point P(x,y) (which is not the origin). How can I do that?

I'm using the lm command in R and the basic fitting GUI in Matlab. I think that I could use the constrOptim command (in R) or translate the origin into the point P, but I'm wondering if there's a specific command to do that.

I only need the solution for one of these programs, then I can use the coefficients in the other one.

ac2051
  • 354
  • 1
  • 2
  • 15

1 Answers1

5

Just center the data appropriately and force the regression through the 'origin':

lm(y ~ I(x-x0)-1, offset=rep(y0,nrow(dat)) data=dat)

You might then need to adjust the intercept coefficient accordingly.

edited: offset needs to be a vector of the correct length. Another way to do this would be:

set.seed(1)
d <- data.frame(x=1:10,y=rnorm(10,mean=1:10,sd=0.1))
x0 <- 3
y0 <- 3
(lm1 <- lm(y ~ I(x-x0)-1, offset=y0, data=data.frame(d,y0)))

This gives a slope of 1.005. The intercept would be coef(lm1)*(-y0/x0), I think.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • I've tried as you say with `x0 <- 3.15 y0 <-283.56 regression <- lm(y ~ I(x-x0)-1, offset=y0)` (I think that `data = dat` is not necessary in this case) but I have this error : `Error in model.frame.default(formula = y ~ I(x - x0) - 1, : variable lengths differ (found for '(offset)')`. I don't understand why.. – ac2051 Jun 03 '13 at 21:58
  • Thanks for your answer. I've asked how _offset_ works in [another question](http://stackoverflow.com/q/16920628/2271092). – ac2051 Jun 04 '13 at 14:41
  • Thanks a lot for editing the question! Both of the solutions you've proposed work. – ac2051 Jun 04 '13 at 16:20