Rのフォーミュラ

R における Generalized Linear Models

Richard Erickson

Instructor

多項ロジスティック回帰でフォーミュラを理解する重要性

  • フォーミュラは回帰の基盤
  • 理解が難しい
  • model.matrix() の理解が重要
R における Generalized Linear Models

傾き

  • 連続変数の係数を推定する
    • 例:height = c(72.3, 21.1, 3.7, 1.0)
  • フォーミュラには全体の切片も必要
  • 複数の傾き:予測変数ごとに傾きを推定
R における Generalized Linear Models

切片

  • 離散グループを予測に使用
  • Rのfactorまたはcharacter:fish = c("red", "blue")
  • 単一の切片に2つの選択肢:
    • 参照切片+対比:y ~ x
    • 各グループの切片:y ~ x -1
R における Generalized Linear Models

複数の切片

  • 参照グループと比較した各グループの効果を推定
  • factorの中でアルファベット順に最初のグループ
  • デフォルトでは変数ごとに参照グループが1つ
    • y ~ x1 + x2
  • 全グループの切片を推定するグループを指定可能
    • y ~ x1+ x2 - 1
  • 最初の変数は各グループの切片を推定
R における Generalized Linear Models

ダミー変数

  • グループの所属を符号化する
  • 内部で使用(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 における Generalized Linear Models

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またはRfactor()で順序を変更できる
R における Generalized Linear Models

factorと数値の注意点

  • 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 における Generalized Linear Models

練習しましょう!

R における Generalized Linear Models

Preparing Video For Download...