r - 如何将一列(逗号拆分)转换为 R 中的多列?

标签 r dplyr tidyverse tidyr one-hot-encoding

<分区>

例如,我有这个数据:

data <- data.frame(person=paste0("person_", 1:5),
                   keyword=sapply(1:5, function(x) paste0(sample(letters, sample(1:5, 1)), collapse = ","))
                   )
> data
    person keyword
1 person_1 k,f,p,w
2 person_2     y,j
3 person_3     y,r
4 person_4     g,w
5 person_5 u,x,c,n

我想将关键字拆分成多个列,并最终将它们转换为二进制数据,如下所示:

    person k f p w y j r g w u x c n 
1 person_1 1 1 1 1 0 0 0 0 0 0 0 0 0
2 person_2 0 0 0 0 1 1 0 0 0 0 0 0 0 
3 person_3 0 0 0 0 1 0 1 0 0 0 0 0 0
4 person_4 0 0 0 0 0 0 0 1 1 0 0 0 0
5 person_5 0 0 0 0 0 0 0 0 0 1 1 1 1

实现此目标的最佳方法是什么?

谢谢。

最佳答案

你可以使用

library(tidyr)
library(dplyr)

data %>% 
  mutate(keyword = strsplit(keyword, ",")) %>% 
  unnest(keyword) %>% 
  mutate(value = 1) %>% 
  pivot_wider(names_from = keyword, values_fill = 0)

返回

# A tibble: 5 x 16
  person       p     f     i     u     r     v     q     j     d     k     x     o     c     s     b
  <chr>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 person_1     1     1     1     0     0     0     0     0     0     0     0     0     0     0     0
2 person_2     0     0     0     1     1     1     1     1     0     0     0     0     0     0     0
3 person_3     0     0     0     0     0     1     0     1     1     1     0     0     0     0     0
4 person_4     0     0     0     0     0     0     0     0     0     0     1     0     0     0     0
5 person_5     0     0     0     0     0     0     0     0     0     0     1     1     1     1     1

关于r - 如何将一列(逗号拆分)转换为 R 中的多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68719120/

相关文章:

r - 将侧面添加到具有多个变量值的点图中

html - knitr html 输出中的字符串太长

r - 按一列分组并折叠所有其他列而无需 NA

r - 使用 %>% 运算符获取向量中特定元素的索引

r - 如何使用 tidyr 自动创建变量?

r - 填充矩阵,其中子矩阵是 R 中向量(向量可以是随机数)中值的维度

r - dplyr | group_by 与 anti_join |最有效的方法

r - 动态规范化组中第一个元素的所有行

r - 如何将列表列表转换为小标题(数据框)

r - Tidyverse 和 R : how to count rows in a tibble of a nested dataframe