d <- data.frame(ResState=c('CA', 'NV', 'OR', 'CA', 'CA', NA, 'WA', 'OR', 'WA'))
print(d)
## ResState
## 1 CA
## 2 NV
## 3 OR
## 4 CA
## 5 CA
## 6 <NA>
## 7 WA
## 8 OR
## 9 WA
print(model.matrix(~ResState,data=d))
## (Intercept) ResStateNV ResStateOR ResStateWA
## 1 1 0 0 0
## 2 1 1 0 0
## 3 1 0 1 0
## 4 1 0 0 0
## 5 1 0 0 0
## 7 1 0 0 1
## 8 1 0 1 0
## 9 1 0 0 1
## attr(,"assign")
## [1] 0 1 1 1
## attr(,"contrasts")
## attr(,"contrasts")$ResState
## [1] "contr.treatment"
# row 6 missing!
d$ResState <- addNA(d$ResState,ifany=TRUE)
print(model.matrix(~ResState,data=d))
## (Intercept) ResStateNV ResStateOR ResStateWA ResStateNA
## 1 1 0 0 0 0
## 2 1 1 0 0 0
## 3 1 0 1 0 0
## 4 1 0 0 0 0
## 5 1 0 0 0 0
## 6 1 0 0 0 1
## 7 1 0 0 1 0
## 8 1 0 1 0 0
## 9 1 0 0 1 0
## attr(,"assign")
## [1] 0 1 1 1 1
## attr(,"contrasts")
## attr(,"contrasts")$ResState
## [1] "contr.treatment"
print(model.matrix(~0+ResState,data=d))
## ResStateCA ResStateNV ResStateOR ResStateWA ResStateNA
## 1 1 0 0 0 0
## 2 0 1 0 0 0
## 3 0 0 1 0 0
## 4 1 0 0 0 0
## 5 1 0 0 0 0
## 6 0 0 0 0 1
## 7 0 0 0 1 0
## 8 0 0 1 0 0
## 9 0 0 0 1 0
## attr(,"assign")
## [1] 1 1 1 1 1
## attr(,"contrasts")
## attr(,"contrasts")$ResState
## [1] "contr.treatment"
# two incompatible factors
f1 <- factor(c("a","b","c"))
print(f1)
## [1] a b c
## Levels: a b c
print(as.numeric(f1))
## [1] 1 2 3
print(attr(f1,'levels'))
## [1] "a" "b" "c"
f2 <- factor(c("a","b","c"),levels=c("c","b","a"))
print(f2)
## [1] a b c
## Levels: c b a
print(as.numeric(f2))
## [1] 3 2 1