Given an array of length 6 of 3 unique numbers, say:
c(1,1,1,2,3,3)
How can I construct the following 6x3 matrix:
[1, 0 , 0]
[1, 0 , 0]
[1, 0 , 0]
[0, 1 , 0]
[0, 0, 1]
[0, 0, 1]
A naive way would be:
V = c(1,1,1,2,3,3)
Z = matrix(0,6,3)
for (i in 1:6) {Z[i, V[i]] = 1}
but is there a nice one liner for this type of operation?
We may use
model.matrix
inbase R
-output
Or use
dummy_cols
fromfastDummies
data