具有二进制输出的r中的透视表

具有二进制输出的r中的透视表,r,R,我有以下数据集 #datset id attributes value 1 a,b,c 1 2 c,d 0 3 b,e 1 我希望用它们制作一个透视表,并将二进制值分配给属性(如果属性存在,则将1分配给属性,否则将0分配给属性)。我的理想输出如下: #output id a b c d e Value 1 1 1 1 0 0 1 2 0 0 1 1 0 0

我有以下数据集

#datset

id  attributes  value
1   a,b,c        1
2   c,d          0
3   b,e          1
我希望用它们制作一个透视表,并将二进制值分配给属性(如果属性存在,则将1分配给属性,否则将0分配给属性)。我的理想输出如下:

#output

id  a   b   c   d   e   Value
1   1   1   1   0   0   1
2   0   0   1   1   0   0
3   0   1   0   0   1   1

任何提示都非常感谢

我们将“属性”列按“,”拆分,从
qdapTools
cbind
的第一列和第三列中使用
mtabulate
获取频率

library(qdapTools)
cbind(df1[1], mtabulate(strsplit(df1$attributes, ",")), df1[3])
#  id a b c d e value
#1  1 1 1 1 0 0     1
#2  2 0 0 1 1 0     0
#3  3 0 1 0 0 1     1
以R为基数:

attributes <- sort(unique(unlist(strsplit(as.character(df$attributes), split=','))))
cols <- as.data.frame(matrix(rep(0, nrow(df)*length(attributes)), ncol=length(attributes)))
names(cols) <- attributes
df <- cbind.data.frame(df, cols)
df <- as.data.frame(t(apply(df, 1, function(x){attributes <- strsplit(x['attributes'], split=','); x[unlist(attributes)] <- 1;x})))[c('id', attributes, 'value')]
df
  id a b c d e value
1  1 1 1 1 0 0     1
2  2 0 0 1 1 0     0
3  3 0 1 0 0 1     1
属性