Split a column into multiple binary dummy columns [duplicate]

We can use mtabulate from qdapTools after splitting (strsplit(..) the ‘features’ column.

library(qdapTools)
cbind(sampledf[1],mtabulate(strsplit(as.character(sampledf$features), ':')))
#  vin f1 f2 f3 f4 f5
#1  v1  1  1  1  0  0
#2  v2  0  1  0  1  1
#3  v3  1  0  0  1  1

Or we can use cSplit_e from library(splitstackshape)

library(splitstackshape)
df1 <- cSplit_e(sampledf, 'features', ':', type="character", fill=0, drop=TRUE)
names(df1) <-  sub('.*_', '', names(df1))

Or using base R methods, we split as before, set the names of the list elements from the strsplit with ‘vin’ column, convert to a key/value columns ‘data.frame’ using stack, get the table, transpose and cbind with the first column of ‘sampledf’.

cbind(sampledf[1],  
 t(table(stack(setNames(strsplit(as.character(sampledf$features), ':'), 
              sampledf$vin)))))

Leave a Comment