在一列中使用多个分隔符

huangapple go评论114阅读模式
英文:

Multipler delimiters in a column

问题

结果列中有多个答案,用',''/'分隔。需要计算每个答案的实例数。

在一列中使用多个分隔符

我想要的结果是

在一列中使用多个分隔符

我不知道如何拆分第一个表格中的答案列。我对字符串拆分一窍不通。

我尝试过在数据框中使用strsplit和str_split,并将列转换为列表,然后尝试使用它们,但是这样做很混乱,并且一直给我各种错误消息。我接近成功了

df %>% separate_longer_delim(Answers, delim = ',/')

但是我无法让delim部分起作用。我可以使用逗号或斜杠,但不能同时使用两者。

英文:

Column of results with multiple answers separated by ',' or '/'. Need to count the instances of each response.

在一列中使用多个分隔符

What I want to end up with is

在一列中使用多个分隔符

I'm at a loss how to split the Answers column in the first table. I'm terrible with string splits.

I've tried using both strsplit and str_split as part of the data frame and turning the column into a list and trying them that way, but it was messy and keep giving me various error messages. I'm close with

df %>% separate_longer_delim(Answers, delim = ',/')

But I can't get the delim part to work. I can use either the comma or the slash but not both together.

答案1

得分: 4

根据separate_longer_delim文档的描述:

> delim:默认情况下,它被解释为固定字符串;使用stringr::regex()和相关函数以其他方式进行分割。

library(tidyr)
library(dplyr)

df %>% 
  separate_longer_delim(Answers, stringr::regex("[,/]\\s*")) %>% 
  count(Answers, sort = TRUE)

#          Answers n
# 1           cars 2
# 2           dirt 2
# 3           toys 2
# 4 all the things 1
# 5          dolls 1
# 6         trucks 1
数据
df <- data.frame(id = 1:4, Answers = c("toys, dirt", "cars, dolls", "cars/toys/dirt", "all the things, trucks"))
英文:

As described in the document of separate_longer_delim:

> delim: By default, it is interpreted as a fixed string; use stringr::regex() and friends to split in other ways.

library(tidyr)
library(dplyr)

df %&gt;%
  separate_longer_delim(Answers, stringr::regex(&quot;[,/]\\s*&quot;)) %&gt;%
  count(Answers, sort = TRUE)

#          Answers n
# 1           cars 2
# 2           dirt 2
# 3           toys 2
# 4 all the things 1
# 5          dolls 1
# 6         trucks 1
Data
df &lt;- data.frame(id = 1:4, Answers = c(&quot;toys, dirt&quot;, &quot;cars, dolls&quot;, &quot;cars/toys/dirt&quot;, &quot;all the things, trucks&quot;))

huangapple
  • 本文由 发表于 2023年8月10日 21:15:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定