簡單直線回歸 (Simple Linear Regression)

套路41: 簡單直線回歸 (Simple Linear Regression)

1. 使用時機: 以單一變數(自變數)預測判斷依變數與自變數之間相關的方向(趨勢)和程度。
2. 分析類型: 母數分析(parametric analysis)
3. 範例資料: 咪路測量手養鳥出生天數(day)與翅膀長度(cm)資料如下:
X (day)        
1
3
4
6
9
10
12
15
17
19
23
25
27
Y (翼長)
1.4
1.5
2.2
2.4
3.1
3.2
3.5
3.9
4.1
4.5
4.7
5.0
5.2
  XY是否有線性關係?
4. 輸入建立資料:
  dat <- read.table(header = T, text = "
age length
1 1.4
3 1.5
4 2.2
6 2.4
9 3.1
10 3.2
12 3.5
15 3.9
17 4.1
19 4.5
23 4.7
25 5.0
27 5.2")  # agelength資料以空白分隔
  attach(dat)  # 告知R使用資料dat
  names(dat)  # 指定資料標題。

5. 畫圖看資料分佈:
: 安裝ggplot2程式套件。
第二步: 呼叫ggplot2程式套件備用
  library(ggplot2)
第三步: 使用ggplot2程式套件的函數ggplot代入datagelengthx-y散佈圖及回歸線
  ggplot(dat, aes(x = age, y = length)) +
    geom_point(shape=1) +    # 畫空心圓
    geom_smooth(method=lm)   # 加回歸線                   
# 灰色區域為95%信賴區間

6. 使用R計算回歸方程式:
第一步: 閱讀基本模組(base)lm函數的使用說明。
  help(lm)
第二步: 使用基本模組(base)lm函數代入datagelength計算回歸線,結果儲存於變數model
  model <- lm(length ~ age, data = dat)
第三步: 使用基本模組(base)函數summary代入變數model顯示結果
  summary(model)
第四步: 判讀結果
Call:
lm(formula = length ~ age, data = dat)
Residuals:
    Min      1Q  Median      3Q     Max
-0.4622  -0.1700  0.0924     0.2116   0.2655
Coefficients:
            Estimate Std. Error t value Pr(>|t|)   
(Intercept)   1.526048   0.129014   11.83 1.35e-07 ***  # 直線方程式截距
age         0.145388   0.008295   17.53 2.19e-09 ***  # 直線方程式斜率
  # 直線方程式: y = 0.145388x + 1.526048
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.2482 on 11 degrees of freedom
Multiple R-squared:  0.9654,    Adjusted R-squared:  0.9623
  # R2: the coefficient of determination越接近1資料與回歸線越符合(fit)
F-statistic: 307.2 on 1 and 11 DF,  p-value: 2.19e-09
  # H0: b = 0HA: b ≠ 0
  # p-value < 0.05H0: b = 0不成立,回歸線斜率不為0
  # p-value > 0.05H0: b = 0成立,回歸線斜率為0,此回歸線無用。

來勁了嗎? 想知道更多?? 補充資料(連結):
1. 關於Simple linear regression (https://en.wikipedia.org/wiki/Simple_linear_regression)
4. 關於R基礎R繪圖及統計快速入門:
   b. Cookbook for R: http://www.cookbook-r.com/
   d. Statistical tools for high-throughput data analysis (STHDA): http://www.sthda.com/english/
e. The Handbook of Biological Statistics: http://www.biostathandbook.com/
f. An R Companion for the Handbook of Biological Statistics: http://rcompanion.org/rcompanion/index.html
5. Zar, JH. 2010. Biostatistical Analysis, Fifth Edition, Pearson.

留言

這個網誌中的熱門文章

統計不球人 目錄 (Table of Contents)

三因子變異數分析 (Three Way ANOVA)

比較二或多組變異數Levene’s 檢定 (Levene’s Test for Comparing Two or More Variances)