R: Incidence matrix

From MathWiki

To generate an incidence matrix for a variable X:

 > Im <- contrasts( as.factor(X), contrasts = FALSE)[ as.factor(X), ]

For example:

 > X <- c(1,2,3,1,3,NA,2)
 > contrasts( as.factor(X), contrasts = FALSE)[ as.factor(X), ]      
       1  2  3
 1     1  0  0
 2     0  1  0
 3     0  0  1
 1     1  0  0
 3     0  0  1
 <NA> NA NA NA
 2     0  1  0