r语言 - 具有多个标签的独热编码功能



在python中,我们可以制作具有多个标签的One-Hot Encode功能示例:https://chrisalbon.com/machine_learning/preprocessing_structured_data/one-hot_encode_features_with_multiple_labels/

我有一个包含几列的数据框,最后一列是标签。

此标签是这样的列表(每行一个新行(:

Label
"A"
"B"
"C"
"D"
"A,B,C"
"A,C"
"D,B,A"
"D,C,B,A"

我尝试:

levels(data_Frame$Label)<-c("A","B","C","D")
New_data_Frame<-as.data.frame(decodeClassLabels(data_Frame$Label))

但我得到的是:

A   B   C   D
1   0   0   0
0   1   0   0 
0   0   1   0 
0   0   0   1 
0   0   0   0 
0   0   0   0 
0   0   0   0
0   0   0   0 

我想要的是:

A   B   C   D
1   0   0   0
0   1   0   0 
0   0   1   0 
0   0   0   1 
1   1   1   0 
1   0   1   0 
1   1   0   1
1   1   1   1 

一种选择是按,拆分"标签"列,然后使用mtabulate

library(qdapTools)
+(mtabulate(strsplit(df1$Label, ",")) > 0) 
#     A B C D
#[1,] 1 0 0 0
#[2,] 0 1 0 0
#[3,] 0 0 1 0
#[4,] 0 0 0 1
#[5,] 1 1 1 0
#[6,] 1 0 1 0
#[7,] 1 1 0 1
#[8,] 1 1 1 1

数据

df1 <- structure(list(Label = c("A", "B", "C", "D", "A,B,C", "A,C", 
"D,B,A", "D,C,B,A")), class = "data.frame", row.names = c(NA, 
  -8L))

最新更新