【问题标题】:Tidytext R - find and replaceTidytext R - 查找和替换
【发布时间】:2021-12-17 17:52:12
【问题描述】:

我有一项调查的结果,其中一堆答案有错误,例如拼写错误、UppercAseS/小写……

因此,我需要类似查找和替换的解决方案(我找到了一些可能的功能,但它们似乎都不起作用。我有点不喜欢)

...但不是一个一个地查找和替换,我想创建一个“错误”的向量(?),然后用正确的答案替换它们,整理我的文本以便以后能够可视化结果.

我试过了

将 VAR1 视为遮阳篷:

VAR1 <- c("motorbyke","motor bike","Mbike","Motor   B","Motor","Bike")

我想把拼错的遮阳篷改成正确的;比如说“摩托车”……

DB %>% 
mutate(VAR1 = replace(VAR1, VAR1 == "misspelling", "correct answer")) 

但是单独做会出错太多...

我的困境有什么解决办法吗?

谢谢

编辑:尝试添加示例

【问题讨论】:

  • 请提供最小可重现的假数据来证明和验证!
  • 用示例编辑...?

标签: r tidytext


【解决方案1】:

这是使用 tidyverse 和 left_joins 的一种可能解决方案:

DB <- data.frame(
  VAR1=c(c("motorbyke","motor bike","Mbike","Motor   B","Motor","Bike"), 
         sample(stringr::words, 10)))

correction_df <- data.frame(
  cbind(correction="motorbike", incorrect=c("motorbyke","motor bike","Mbike","Motor   B","Motor","Bike"))
)

DB %>%
  left_join(correction_df, by=c(VAR1="incorrect")) %>%
  mutate(VAR1=ifelse(is.na(correction), VAR1, correction)) %>%
  select(-correction)

可以使用提供的语法将新条目添加到correction_df。或者,fuzzyjoin package 做了一些非常相似的事情,并且可能会自动执行您感兴趣的一些更正。

【讨论】:

    【解决方案2】:

    您可以为向量的str_replace 创建一个模式,然后将所有这些替换为motorbike(在列或向量等中......)

    VAR1 <- c("motorbyke","motor bike","Mbike","Motor   B","Motor","Bike")
    
    my_pattern <- paste(VAR1, collapse = "|")
    
    
    library(stringr)
    str_replace(VAR1, my_pattern, 'motorbike')
    

    输出:

    [1] "motorbike" "motorbike" "motorbike" "motorbike" "motorbike" "motorbike"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 2014-09-01
      • 1970-01-01
      相关资源
      最近更新 更多