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

我正在尝试将数据框中的单个“字符”变量拆分为多个“因子”变量。


> 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()分隔“功能”列


strsplit(as.character(df$features), ";") 

但是没有运气可以分解它们。


海绵宝宝撒
浏览 403回答 1
1回答

噜噜哒

我们可以使用mtabulate从qdapTools拆分后(strsplit(..)的“功能”一栏。library(qdapTools)cbind(sampledf[1],mtabulate(strsplit(as.character(sampledf$features), ':')))#&nbsp; vin f1 f2 f3 f4 f5#1&nbsp; v1&nbsp; 1&nbsp; 1&nbsp; 1&nbsp; 0&nbsp; 0#2&nbsp; v2&nbsp; 0&nbsp; 1&nbsp; 0&nbsp; 1&nbsp; 1#3&nbsp; v3&nbsp; 1&nbsp; 0&nbsp; 0&nbsp; 1&nbsp; 1或者我们可以使用cSplit_e从library(splitstackshape)library(splitstackshape)df1 <- cSplit_e(sampledf, 'features', ':', type= 'character', fill=0, drop=TRUE)names(df1) <-&nbsp; sub('.*_', '', names(df1))还是使用base R方法,我们split像以前一样,在with'vin'列中设置list元素的名称,strsplit使用stack,获取table,转置和cbind在'sampledf'的第一列中将其转换为键/值列'data.frame'。cbind(sampledf[1],&nbsp;&nbsp;&nbsp;t(table(stack(setNames(strsplit(as.character(sampledf$features), ':'),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sampledf$vin)))))
打开App,查看更多内容
随时随地看视频慕课网APP