สูตร (Formulas) ใน R

Generalized Linear Models ใน R

Richard Erickson

Instructor

ทำไมต้องใส่ใจเรื่อง formulas สำหรับ multiple logistic regression?

  • Formulas คือแกนหลักของ regression
  • ทำความเข้าใจได้ไม่ง่ายนัก
  • เข้าใจ model.matrix() คือกุญแจสำคัญ
Generalized Linear Models ใน R

Slopes

  • ประมาณค่าสัมประสิทธิ์ของตัวแปรต่อเนื่อง
    • เช่น height = c(72.3, 21.1, 3.7, 1.0)
  • Formula ยังต้องการ global intercept ด้วย
  • หลาย slope: มี slope สำหรับแต่ละ predictor
Generalized Linear Models ใน R

Intercepts

  • ใช้กลุ่มแบบ discrete เพื่อพยากรณ์
  • factor หรือ character ใน R: fish = c("red", "blue")
  • Single intercept มีสองแบบ:
    • Reference intercept + contrast: y ~ x
    • Intercept สำหรับแต่ละกลุ่ม: y ~ x -1
Generalized Linear Models ใน R

Multiple intercepts

  • ประมาณผลของแต่ละกลุ่มเทียบกับ reference group
  • กลุ่มแรกตามลำดับตัวอักษรใน factor
  • ค่าเริ่มต้นมี reference group หนึ่งกลุ่มต่อตัวแปร
    • y ~ x1 + x2
  • ระบุกลุ่มเดียวเพื่อประมาณ intercept สำหรับทุกกลุ่มได้
    • y ~ x1+ x2 - 1
  • ตัวแปรแรกมี intercept ประมาณแยกสำหรับแต่ละกลุ่ม
Generalized Linear Models ใน R

Dummy variables

  • เข้ารหัสสมาชิกภาพในกลุ่ม
  • ใช้งานภายใน (เช่น model.matrix())
  • ใช้ 0 และ 1 สำหรับแต่ละกลุ่ม
  • ตัวอย่างอินพุต: color = c("red", "blue")
  • Dummy variables สำหรับ y ~ colors:
    • intercept = c(1, 1)
    • blue = c(0, 1)
  • Dummy variables สำหรับ y ~ colors - 1 :
    • red = c(1, 0)
    • blue = c(0, 1)
Generalized Linear Models ใน R

model.matrix()

  • model.matrix() ทำงานหนักให้เรา
  • เป็นรากฐานของ formulas ใน 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()
Generalized Linear Models ใน 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"
Generalized Linear Models ใน R

มาฝึกกันเถอะ!

Generalized Linear Models ใน R

Preparing Video For Download...