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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.