Data that looks like this:
library(data.table) DT <- data.table(x=rep(1:5, 2))
I would like to break this data into 5 boolean columns that indicate the presence of each number.
I can do it like this:
new.names <- sort(unique(DT$x)) DT[, paste0('col', new.names) := lapply(new.names, function(i) DT$x==i), with=FALSE]
But this uses pesky lapply
, which is probably slower than the alternative to data.table, and this solution seems to me not very "data.table-ish".
Is there a better and / or faster way to create these new columns?
source share