R:用最常见的变体替换字符串

标签 r tidyverse recode

我希望标准化一组手动输入的字符串,以便:

index   fruit
1   Apple Pie
2   Apple Pie.
3   Apple. Pie
4   Apple Pie
5   Pear

应该看起来像:

index   fruit
1   Apple Pie
2   Apple Pie
3   Apple Pie
4   Apple Pie
5   Pear

对于我的用例,按 phonetic 对它们进行分组声音很好,但我缺少有关如何用最常见的字符串替换最不常见的字符串的部分。

library(tidyverse)  
library(stringdist)

index <- seq(1,5,1)
fruit <- c("Apple Pie", "Apple Pie.", "Apple. Pie", "Apple Pie", "Pear")

df <- data.frame(index, fruit) %>%
  mutate(grouping = phonetic(fruit)) %>%
  add_count(fruit) %>%
  # Missing Code
  select(index, fruit)

最佳答案

听起来您需要group_by分组,然后选择最常见的(模式)项目

df%>%mutate(grouping = phonetic(fruit))%>%
     group_by(grouping)%>%
     mutate(fruit = names(which.max(table(fruit))))

# A tibble: 5 x 3
# Groups:   grouping [2]
  index     fruit grouping
  <dbl>    <fctr>    <chr>
1     1 Apple Pie     A141
2     2 Apple Pie     A141
3     3 Apple Pie     A141
4     4 Apple Pie     A141
5     5      Pear     P600

关于R:用最常见的变体替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56651367/

相关文章:

r - 控制knitr中两个并排图的对齐

r - 如何按顺序编码多列并删除 tidyverse 中的重复数据

r - 是否有任何明确保证 dplyr 操作保留行顺序?

在 R 中重新编码任意分组变量或因子

将日期重新编码为主题内的学习日

r - 打印 <0.001 的 p 值

r - 在 count=0 的情况下,如何使用 geom_bar() 去除 ggplot2 图的更宽条

r - 有没有一种简单的方法来重新编码因子变量的级别,以便将低于给定频率的级别重新编码为 "other"

r - R 中 model.matrix 中有序因子的列名称

r - 用于可视化或过滤 P 值的整洁 chisq.test 输出的函数