R 将列拆分为多个二进制伪列

R 将列拆分为多个二进制伪列,r,dataframe,R,Dataframe,我试图将数据帧中的单个“字符”变量拆分为多个“因子”变量 > sampledf=data.frame(vin=c('v1','v2','v3'),features=c('f1:f2:f3','f2:f4:f5','f1:f4:f5')) > sampledf vin features 1 v1 f1:f2:f3 2 v2 f2:f4:f5 3 v3 f1:f4:f5 > desireddf=data.frame(vin=c('v1','v2','v3'),f1=c(

我试图将数据帧中的单个“字符”变量拆分为多个“因子”变量

> sampledf=data.frame(vin=c('v1','v2','v3'),features=c('f1:f2:f3','f2:f4:f5','f1:f4:f5'))
> sampledf
  vin features
1  v1 f1:f2:f3
2  v2 f2:f4:f5
3  v3 f1:f4:f5

> desireddf=data.frame(vin=c('v1','v2','v3'),f1=c(1,0,1),f2=c(1,1,0),f3=c(1,0,0),f4=c(0,1,1),f5=c(0,1,1))
> desireddf
  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
我尝试使用
strsplit()
来分隔“features”列


但是没有运气将它们分解。

我们可以在拆分(
strsplit(…
)“功能”列后使用
qdapTools
中的
mtabulate

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
或者我们可以使用
cSplit\u e
from
library(splitstackshape)


它们在akrun中工作得非常好!但是有没有办法使用基函数来实现这一点呢?@outlier123添加了一个基R选项。太棒了!非常感谢akrun!!(代表太低,无法公开投票)
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
library(splitstackshape)
df1 <- cSplit_e(sampledf, 'features', ':', type= 'character', fill=0, drop=TRUE)
names(df1) <-  sub('.*_', '', names(df1))
cbind(sampledf[1],  
 t(table(stack(setNames(strsplit(as.character(sampledf$features), ':'), 
              sampledf$vin)))))