Skip to content

Instantly share code, notes, and snippets.

@GabrielHoffman
Last active August 13, 2020 01:32
Show Gist options
  • Save GabrielHoffman/9023fbb639650e7768d36e2d9965ef86 to your computer and use it in GitHub Desktop.
Save GabrielHoffman/9023fbb639650e7768d36e2d9965ef86 to your computer and use it in GitHub Desktop.
# simulate design matrix wti Dx with 3 categories and Sex with 2
# A: Control
# B: Schiz
# C: Other
info = data.frame(Dx = sample(LETTERS[1:3], 100, replace=TRUE),
Sex = sample(c('M', 'F'), 100, replace=TRUE))
table(info$Dx)
#>
#> A B C
#> 39 29 32
table(info$Sex)
#>
#> F M
#> 48 52
# Marginal terms
colnames(model.matrix(~ Dx + Sex, info))
#> [1] "(Intercept)" "DxB" "DxC" "SexM"
colnames(model.matrix(~ 0+Dx + Sex, info))
#> [1] "DxA" "DxB" "DxC" "SexM"
# Interaction terms
colnames(model.matrix(~ Dx*Sex, info))
#> [1] "(Intercept)" "DxB" "DxC" "SexM" "DxB:SexM"
#> [6] "DxC:SexM"
colnames(model.matrix(~ 0+Dx*Sex, info))
#> [1] "DxA" "DxB" "DxC" "SexM" "DxB:SexM" "DxC:SexM"
# Interaction by crossing categories
info$Dx_Sex = with(info, paste(Dx, Sex, sep='.'))
colnames(model.matrix(~Dx_Sex, info))
#> [1] "(Intercept)" "Dx_SexA.M" "Dx_SexB.F" "Dx_SexB.M" "Dx_SexC.F"
#> [6] "Dx_SexC.M"
colnames(model.matrix(~0+Dx_Sex, info))
#> [1] "Dx_SexA.F" "Dx_SexA.M" "Dx_SexB.F" "Dx_SexB.M" "Dx_SexC.F" "Dx_SexC.M"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment