Suppose I have the following data table in R:
DT <- data.table::data.table(y=runif(1e4), x1=rnorm(1e4), x2=as.factor(sample(1:11,1e4,TRUE)))
Since x2 takes value 1 to 11, the maximum binary representation for 11 is 1011, so 4 columns would be enough, I want to convert x2 to 4 binary columns such that:
y x1 x2 b1 b2 b3 b4
0.17438022 0.1925023 11 1 0 1 1
0.34850700 1.0412363 3 0 0 1 1
How to do it in R?