You are on page 1of 4

R 講義(7) 江俊佑製

簡單線性回歸分析(上)

1、 相關分析
假設我們想要了解 X 和 Y 之間到底有沒有關係存在,方法如下:

 散佈圖

指令: plot( ) or matplot( )

 相關係數

指令: cor(x, y)

 檢定 ρ = 0

指令: cor.test(x, y, conf.level = 0.95)

EX1: 某研究單位想要了解身高與體重之間的關係,所以隨機從年紀均為 18 歲
的女生中抽出 14 位,資料如下:

身高(公分) 體重(公斤) 身高(公分)) 體重(公斤)


165 48 166 51
158 43 168 52
153 43 170 55
161 50 173 55
176 61 165 48
158 50 152 43
158 48 155 46

判別此筆資料中的身高與體重是否有關係。

>
height=c(165,158,153,161,176,158,158,166,168,170,173,165,15
2,155)
> weight=c(48,43,43,50,61,50,48,51,51,55,55,48,43,46)
> matplot(height,weight,col="orange3",pch=16,cex=2)
> #------------- cor( ) -----------------

3
R 講義(7) 江俊佑製

> cor(height,weight)
[1] 0.9025936
> #------------- cor.test( ) -----------------
> cor.test(height, weight, conf.level = 0.95)

Pearson's product-moment correlation

data: height and weight


t = 7.263, df = 12, p-value = 9.968e-06
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
0.7138983 0.9690820
sample estimates:
cor
0.9025936

2、 簡單線性迴歸
單線性迴歸(simple linear regression)是由一個自變數和一個應變數所
構成,其統計模型定義為:
Yi = β 0 + β1 X i + ε i i = 1,..., n
其中, X i 為自變數, Yi 為應變數, εi 為獨立的隨機誤差項,並且滿足
E (ε i ) = 0 和 Var (ε i ) = σ 2 的常態分配。
回歸分析的指令為:

summary(lm(formula))

其中,formula 為統計模型,也就是說,在簡單線性迴歸的情況下,如果我們
的統計模型為 Yi = β0 + β1 X i + ε i ,則在 R 裡的寫法為 Y~X。

3
R 講義(7) 江俊佑製

迴歸分析中的 ANOVA 表的指令為:

anova(lm(formula))

其中,formula 為統計模型,也就是說,在簡單線性迴歸的情況下,如果我們
的統計模型為 Yi = β0 + β1 X i + ε i ,則在 R 裡的寫法為 Y~X。

β0 和 β1 的 100(1- α )%信賴區間指令為

confint(lm(formula, level = 0.95)

其中,formula 為統計模型,也就是說,在簡單線性迴歸的情況下,如果我們
的統計模型為 Yi = β0 + β1 X i + ε i ,則在 R 裡的寫法為 Y~X,而 level 表示信賴
水準,內設 0.95。

EX2: 承 EX1,假設身高為自變數,體重為應變數,解釋上述指令所跑出來的
報表。

>
height=c(165,158,153,161,176,158,158,166,168,170,173,165,15
2,155)
> weight=c(48,43,43,50,61,50,48,51,51,55,55,48,43,46)
> summary(lm(weight~height))

Call:
lm(formula = weight ~ height)

Residuals:
Min 1Q Median 3Q Max
-3.49565 -1.49466 -0.07391 1.47095 3.50435

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -51.80158 13.95137 -3.713 0.00296 **
height 0.62213 0.08566 7.263 9.97e-06 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

3
R 講義(7) 江俊佑製

Residual standard error: 2.303 on 12 degrees of freedom


Multiple R-squared: 0.8147, Adjusted R-squared: 0.7992
F-statistic: 52.75 on 1 and 12 DF , p-value: 9.968e-06
> #------------- anova -----------------------
> anova(lm(weight~height))
Analysis of Variance Table

Response: weight
Df Sum Sq Mean Sq F value Pr(>F)
height 1 279.783 279.783 52.751 9.968e-06 ***
Residuals 12 63.646 5.304
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1
> ---------------------- confint( ) --------------------------
> confint (lm(weight~height))
2.5 % 97.5 %
(Intercept) -82.1990101 -21.4041520
height 0.4355015 0.8087672

You might also like