2013-04-22 154 views
14

我想繪製使用abline(lm(...))的最小二乘迴歸線,該線也被迫通過特定點。我看到this question是相關的,但不是我想要的。這裏有一個例子:R draw(abline + lm)通過任意點的最佳擬合線

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

這看起來像:

enter image description here

現在我將如何去有關強制一條線的(x=10,y=50)標記的任意點,同時仍距離儘量減少對其他點?

# force through [10,50] - red line 
?? 

回答

13

一個粗略的解決辦法是爲你的模型轉變原點到這一點,並創建一個模型,沒有攔截

nmod <- (lm(I(y-50)~I(x-10) +0, test)) 

abline(predict(nmod, newdata = list(x=0))+50, coef(nmod), col='red') 

enter image description here

+0

不錯。似乎不是一個粗略的解決方案。 – thelatemail 2013-04-22 06:50:43

+0

粗糙嗎?不是從計算的角度出發,而是從統計的角度出發。 Bill Venables(來自Venables/Ripley MASS)發現了一些關於此主題的咆哮 – 2013-04-22 08:59:40

+0

這就是我的意思。 – mnel 2013-04-22 09:07:08

3

您可以修改公式lm()和偏移數據:

p=10 
q=50 

abline(lm(I(y-q) ~ I(x-p) + 0, data=test), col="red") 
+0

是的。現在編輯。 – Nishanth 2013-04-22 07:44:08

相關問題