Convert a factor column to multiple boolean columns

后端 未结 3 681
一生所求
一生所求 2021-01-18 05:20

Given data that looks like:

library(data.table)
DT <- data.table(x=rep(1:5, 2))

I would like to split this data into 5 boolean columns t

3条回答
  •  日久生厌
    2021-01-18 05:54

    library(data.table)
    DT <- data.table(x=rep(1:5, 2))
    
    # add column with id
    DT[, id := seq.int(nrow(DT))]
    
    # cast long table into wide
    DT.wide <- dcast(DT, id ~ x, value.var = "x", fill = 0, fun = function(x) 1)
    

提交回复
热议问题