我看到过类似的问题,但我还没有找到一个很好的解决方案,我在tidyr
和dplyr
。我有一个不同的文本类别的连接列,我不知道他们的完整列表。这是大数据,我不能确定这个列中的所有类别。我需要为每个ID
将它们全部拆分,并创建一个相应的二进制列,指示该类别是否与ID
对齐。
df <- data.frame(id=c(1,2,3,4,5),
number=c("a,b,d","e,a","c","","k,t"))
df %>% glimpse()
Rows: 5
Columns: 2
$ id <dbl> 1, 2, 3, 4, 5
$ number <chr> "a,b,d", "e,a", "c", "", "k,t"
我想要的数据会像
id a b C d e k t
1 1 1 0 1 0 0 0
2 1 0 1 0 1 0 0
3 0 0 1 0 0 0 0
4 0 0 0 0 0 0 0
5 0 0 0 0 0 1 1
先谢谢你,我希望你说得很清楚。
2条答案
按热度按时间n3schb8v1#
这种方法使用tidyr中的
separate_longer_delim
来分割文本类别,然后借用recipes
中一个方便的伪编码函数进行one-hot编码。创建于2023年3月16日,使用reprex v2.0.2
kqhtkvqz2#
首先使用基R的
strsplit
提取唯一类别,然后获得每个类别的存在,其中lapply
在每行上为grepls
,as.data.frame
为: