R tidyr : use separate function to separate character column with comma-separated text into multiple columns using RegEx

标签 r regex tidyverse tidyr regex-lookarounds

我有以下数据框

df <- data.frame(x=c("one", "one, two", "two, three", "one, two, three"))

看起来像这样

                x
1             one
2        one, two
3      two, three
4 one, two, three

我希望能够将此 x 列分成许多不同的列,一个列对应 x 列中的每个不同单词。基本上我希望最终结果是这样的

    one  two  three
1    1    0     0
2    1    1     0
3    0    1     1
4    1    1     1

我认为为了获取该数据帧,我可能需要能够使用 tidyr 提供的 separate 函数并记录在 here 。然而,这需要了解正则表达式,而我并不擅长。谁能帮我获取这个数据框?

重要提示:我不知道先验的数字,也不知道单词的拼写。

重要示例

它也应该适用于空字符串。例如,如果我们有

df <- data.frame(x=c("one", "one, two", "two, three", "one, two, three", ""))

那么它也应该可以工作。

最佳答案

这是一个基本的 R 解决方案

# split strings by ", " and save in to a list `lst`
lst <- apply(df, 1, function(x) unlist(strsplit(x,", ")))

# a common set including all distinct words
common <- Reduce(union,lst)

# generate matrix which is obtained by checking if `common` can be found in the array in `lst`
dfout <- `names<-`(data.frame(Reduce(rbind,lapply(lst, function(x) +(common %in% x))),row.names = NULL),common)

这样

> dfout
  one two three
1   1   0     0
2   1   1     0
3   0   1     1
4   1   1     1

关于R tidyr : use separate function to separate character column with comma-separated text into multiple columns using RegEx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513737/

相关文章:

r - 如何在 ggplot 中绘制具有可变 bin 宽度的直方图?

python - 使用 REGEX 读取财务报表

regex - Perl 正则表达式问题

r - 以编程方式在 ggplot 中使用 facets 设置轴面

r - 每 N 列拆分数据并使用 R 进行 rbind

r - 使数据框中的所有元素都是唯一的

r - 如何平衡不平衡分类1 :1 with SMOTE in R

r - 当在 geom_text 中定义指南时更改图例符号

python - python 和 regex 模块如何处理反斜杠

r - dplyr::recode 与 stringr::str_detect() 结合使用