You are on page 1of 4

R 講義(7) 江俊佑製

1、 相關分析

 散佈圖

 相關係數

 檢定 ρ = 0

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

EX1: 某研究單位想要了解身高與體重之間的關係，所以隨機從年紀均為 18 歲

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

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)

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、 簡單線性迴歸

Yi = β 0 + β1 X i + ε i i = 1,..., n

E (ε i ) = 0 和 Var (ε i ) = σ 2 的常態分配。

summary(lm(formula))

3
R 講義(7) 江俊佑製

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

anova(lm(formula))

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

confint(lm(formula, 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