I am trying to draw a least squares regression line using abline(lm(...))
that is also forced to pass through a particular point. I see this question is related, but not quite what I want. Here's an example:
test <- structure(list(x = c(0, 9, 27, 40, 52, 59, 76), y = c(50, 68,
79, 186, 175, 271, 281)), .Names = c("x", "y"))
# set up an example plot
plot(test,pch=19,ylim=c(0,300),
panel.first=abline(h=c(0,50),v=c(0,10),lty=3,col="gray"))
# standard line of best fit - black line
abline(lm(y ~ x, data=test))
# force through [0,0] - blue line
abline(lm(y ~ x + 0, data=test), col="blue")
This looks like:
Now how would I go about forcing a line through the marked arbitrary point of (x=10,y=50)
while still minimising the distance to the other points?
# force through [10,50] - red line
??
A rough solution would be to shift the origin for your model to that point and create a model with no intercept
nmod <- (lm(I(y-50)~I(x-10) +0, test))
abline(predict(nmod, newdata = list(x=0))+50, coef(nmod), col='red')
You can modify the formula for lm()
and offset the data:
p=10
q=50
abline(lm(I(y-q) ~ I(x-p) + 0, data=test), col="red")
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