Formules in R

Generalized Linear Models in R

Richard Erickson

Instructor

Waarom letten op formules voor multiple logistische regressie?

  • Formules zijn de ruggengraat van regressie
  • Lastig om uit te vogelen
  • Begrip van model.matrix() is cruciaal
Generalized Linear Models in R

Hellingen

  • Schat coëfficiënt voor continue variabele
    • bijv. height = c(72.3, 21.1, 3.7, 1.0)
  • Formule vereist ook een globale intercept
  • Meerdere hellingen: één per voorspeller
Generalized Linear Models in R

Intercepts

  • Discrete groepen als voorspellers
  • factor of character in R: fish = c("red", "blue")
  • Eén intercept heeft twee opties:
    • Referentie-intercept + contrast: y ~ x
    • Intercept per groep: y ~ x -1
Generalized Linear Models in R

Meerdere intercepts

  • Schat effect van elke groep t.o.v. referentiegroep
  • De eerste groep, alfabetisch, in de factor
  • Standaard één referentiegroep per variabele
    • y ~ x1 + x2
  • Je kunt aangeven om voor alle groepen een intercept te schatten
    • y ~ x1+ x2 - 1
  • Eerste variabele krijgt een intercept per groep geschat
Generalized Linear Models in R

Dummyvariabelen

  • Codeert groepslidmaatschap
  • Gebruikt onder water (zoals model.matrix())
  • 0'en en 1'en per groep
  • Voorbeeldinvoer: color = c("red", "blue")
  • Dummyvariabelen voor y ~ colors:
    • intercept = c(1, 1)
    • blue = c(0, 1)
  • Dummyvariabelen voor y ~ colors - 1 :
    • red = c(1, 0)
    • blue = c(0, 1)
Generalized Linear Models in R

model.matrix()

  • model.matrix() doet het zware werk voor ons
  • Basis voor formules in R
model.matrix( ~ colors)
  (Intercept) colorsred
1           1         1
2           1         0
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$colors
"contr.treatment"
  • Volgorde bepaald door factorvolgorde
  • Verander de volgorde met Tidyverse of factor()
Generalized Linear Models in R

Factor vs numeriek: kanttekening

  • R ziet de variabele als numeriek
    • bijv. 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
  • Moet als factor of character opgegeven worden
    • bijv. 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 in R

Laten we oefenen!

Generalized Linear Models in R

Preparing Video For Download...