Is there a native R function that will take an input vector and return the corresponding binary matrix where the matrix has the same number of columns as unique values in the input vector?
For example, given x <- 1:3, I want to return the following matrix:
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
The functions contrasts gets close, but I can’t seem to get around the n-1 columns returned:
> contrasts(as.factor(x))
2 3
1 0 0
2 1 0
3 0 1
model.matrix()might help here, but you need to suppress the intercept:Something slightly more complex: