将列拆分为多个二进制虚拟列

out*_*123 4 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(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
Run Code Online (Sandbox Code Playgroud)

我已经尝试过strsplit()分开"功能"列

strsplit(as.character(df$features), ";") 
Run Code Online (Sandbox Code Playgroud)

但没有运气因素.

akr*_*run 10

我们可以使用mtabulateqdapTools拆分后(strsplit(..)的"功能"一栏.

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
Run Code Online (Sandbox Code Playgroud)

或者我们可以使用cSplit_elibrary(splitstackshape)

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

或者使用base R方法,我们split像以前一样,设定的名字list从要素strsplit使用带有"VIN"列,转换为一个键/值列"data.frame" stack,得到了table,并转cbind用"sampledf"的第一列.

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