我有以下数据框
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/