R 的公式

R 的廣義線性模型

Richard Erickson

Instructor

為何在多元邏輯斯迴歸要重視公式?

  • 迴歸的核心是公式
  • 寫對不容易
  • 搞懂 model.matrix() 是關鍵
R 的廣義線性模型

斜率

  • 估計連續變數的係數
    • 例如:height = c(72.3, 21.1, 3.7, 1.0)
  • 公式也需要全域截距
  • 多個斜率:每個自變數各有斜率
R 的廣義線性模型

截距

  • 使用離散群組來預測
  • R 中的 factor 或 character:fish = c("red", "blue")
  • 單一截距有兩種作法:
    • 參考截距+對比:y ~ x
    • 各群各有截距:y ~ x -1
R 的廣義線性模型

多個截距

  • 估計各群相對於參考群的效果
  • 參考群是 factor 中字母序的第一個
  • 預設每個變數有一個參考群
    • y ~ x1 + x2
  • 也可指定為所有群估計截距
    • y ~ x1+ x2 - 1
  • 第一個變數對各群皆估計截距
R 的廣義線性模型

虛擬變數

  • 編碼群組歸屬
  • 底層使用(例如 model.matrix()
  • 各群以 0/1 表示
  • 範例輸入:color = c("red", "blue")
  • y ~ colors 的虛擬變數:
    • intercept = c(1, 1)
    • blue = c(0, 1)
  • y ~ colors - 1 的虛擬變數:
    • red = c(1, 0)
    • blue = c(0, 1)
R 的廣義線性模型

model.matrix()

  • model.matrix() 幫你處理繁瑣細節
  • 是 R 公式的基礎
model.matrix( ~ colors)
  (Intercept) colorsred
1           1         1
2           1         0
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$colors
"contr.treatment"
  • 次序由 factor 的順序決定
  • 可用 Tidyverse 或 factor() 調整順序
R 的廣義線性模型

factor 與 numeric 的注意事項

  • R 會把變數當成數值型
    • 例如:month = c(1, 2, 3)
month <- c( 1, 2, 3)
model.matrix( ~ month)
  (Intercept) month
1           1     1
2           1     2
3           1     3
attr(,"assign")
0 1
  • 需要指定為 factor 或 character
    • 例如:month = factor(c( 1, 2, 3))
model.matrix( ~ month)
  (Intercept) month2 month3
1           1      0      0
2           1      1      0
3           1      0      1
attr(,"assign")
0 1 1
attr(,"contrasts")$month
"contr.treatment"
R 的廣義線性模型

一起來練習吧!

R 的廣義線性模型

Preparing Video For Download...