只有具備線性關(guān)系的數(shù)據(jù)才能夠應(yīng)用線性回歸方法進(jìn)行擬合,因此在進(jìn)行回歸分析之前首先要觀察數(shù)據(jù)是否具有線性關(guān)系。對(duì)于沒有明顯線性關(guān)系的數(shù)據(jù)則沒有必要做線性回歸。現(xiàn)在我們擁有X、Y兩組數(shù)據(jù),我們首先觀察一下數(shù)據(jù)是否具有線性關(guān)系。
x <- c(274, 180, 375, 205, 86, 265, 98, 800, 195, 53, 430, 372, 236, 157, 600, 370)
y <- c(162, 120, 223, 131, 67, 169, 81, 192, 116, 55, 252, 234, 144, 103, 250, 212)
lm.reg <- lm(y ~ x + 1)
plot(x,y)
summary(lm.reg)
從散點(diǎn)圖上看,X、Y基本上呈現(xiàn)線性關(guān)系,從結(jié)果上看假設(shè)檢驗(yàn)中p-value均小于0.05,說明數(shù)據(jù)符合一元線性關(guān)系。
Call:
lm(formula = y ~ x + 1)
Residuals:
Min 1Q Median 3Q Max
-96.801 -20.061 -0.433 23.398 59.526
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 80.52707 19.06532 4.224 0.000850 ***
x 0.26034 0.05449 4.778 0.000295 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 41.51 on 14 degrees of freedom
Multiple R-squared: 0.6198, Adjusted R-squared: 0.5927
F-statistic: 22.83 on 1 and 14 DF, p-value: 0.0002946
我們看到Adjusted R-squared: 0.5927,這個(gè)值有點(diǎn)低,理論上講這個(gè)值越接近1越好,值太小說明數(shù)據(jù)有異常點(diǎn),需要我們進(jìn)行殘差分析去除異常點(diǎn)在進(jìn)行回歸分析。
res <- residuals(lm.reg)
plot(abs(res))
identify(abs(res))
殘差圖
我們用鼠標(biāo)點(diǎn)選殘差較大的點(diǎn)作為異常點(diǎn),顯示X、Y的第8個(gè)點(diǎn)為異常點(diǎn)。接著我們?nèi)コ@個(gè)點(diǎn)。
x1 <- x[-8]
y1 <- y[-8]
lm.res(y1~x1+1)
summary(lm.res)
Call:
lm(formula = y1 ~ x1 + 1)
Residuals:
Min 1Q Median 3Q Max
-51.190 -8.939 -0.250 11.014 31.034
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 42.70434 10.72448 3.982 0.00156 **
x1 0.43081 0.03617 11.911 2.29e-08 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 20.03 on 13 degrees of freedom
Multiple R-squared: 0.9161, Adjusted R-squared: 0.9096
F-statistic: 141.9 on 1 and 13 DF, p-value: 2.285e-08
我們看到p-value均小于0.05,并且Adjusted R-squared: 0.9096已經(jīng)比較接近1了,高于上次的0.5927,說明去除異常點(diǎn)后回歸質(zhì)量進(jìn)一步提升,方法有效可用。