Dummify字符列并查找唯一值

Mic*_*ael 4 r dummy-variable

我有一个具有以下结构的数据帧

test <- data.frame(col = c('a; ff; cc; rr;', 'rr; a; cc; e;'))
Run Code Online (Sandbox Code Playgroud)

现在我想从中创建一个数据帧,其中包含测试数据帧中每个唯一值的命名列.唯一值是以';'结尾的值 角色,从空间开始,不包括空间.然后,对于列中的每一行,我希望用1或0填充虚拟列.如下所示

data.frame(a = c(1,1), ff = c(1,0), cc = c(1,1), rr = c(1,0), e = c(0,1))

  a ff cc rr e
1 1  1  1  1 0
2 1  0  1  1 1
Run Code Online (Sandbox Code Playgroud)

我尝试使用for循环和列中的唯一值创建一个df,但它变得很乱.我有一个可用的向量,包含列的唯一值.问题是如何创建1和0.我尝试了一些mutate_all()功能,grep()但这没用.

Sot*_*tos 8

我使用splitstackshapemtabulateqdapTools包中获得这个作为一个班轮,即

library(splitstackshape)
library(qdapTools)

mtabulate(as.data.frame(t(cSplit(test, 'col', sep = ';', 'wide'))))
#   a cc ff rr e
#V1 1  1  1  1 0
#V2 1  1  0  1 1
Run Code Online (Sandbox Code Playgroud)

它也可以splitstackshape在@ A5C1D2H2I1M1N2O1R2T1评论中提及,

cSplit_e(test, "col", ";", mode = "binary", type = "character", fill = 0)
Run Code Online (Sandbox Code Playgroud)


Dav*_*urg 6

这是一个可能的data.table实现.首先,我们将行分成列,融化成一列并将其展开,同时计算每行的事件

library(data.table)
test2 <- setDT(test)[, tstrsplit(col, "; |;")]
dcast(melt(test2, measure = names(test2)), rowid(variable) ~ value, length)
#    variable a cc e ff rr
# 1:        1 1  1 0  1  1
# 2:        2 1  1 1  0  1
Run Code Online (Sandbox Code Playgroud)