【问题标题】:R: Using sapply or str_replace_all instead of FindReplaceR:使用 sapply 或 str_replace_all 而不是 FindReplace
【发布时间】:2020-11-24 14:45:47
【问题描述】:

示例数据框:

words <- c('Nothing', 'no thing', 'nada', 'nuthin', 'not a thing', 'nothing', 'nothing', 'Nothing', 'nil')
number <- c(1:9)
df <- data.frame(words, number)

在这个df中,我需要用“Nothing”替换所有相当于“nothing”的词。在这个示例 df 中,这就是所有单词,但实际上 df 有许多不应更改的单词。我有一个包含应该更改的单词列表的文本文件,我使用 read_delim 读取了该文件。读入文件后,“更改”在通过 typeof() 运行后显示为“列表”,在通过 class() 运行后显示为“spec_tbl_df”“tbl_df”“tbl”“data.frame”。

我只能从 DataCombine 包中获取 FindReplace 来为我工作。我首先在“更改”中创建了一个替换列,然后通过 FindReplace 运行它。

changes <- mutate(changes, Replacement='Nothing')
df <- FindReplace(df, 'words', changes, from='words', to='Replacement', exact=TRUE, vector=FALSE)

结果就是我想要的。

words    number
Nothing  1
Nothing  2
Nothing  3
Nothing  4
Nothing  5
Nothing  6
Nothing  7
Nothing  8
Nothing  9

但我认为应该有一种方法可以在“更改”上运行循环并使用 sapply 或 str_replace_all 来执行此操作。但我无法让其中任何一个工作。我不断收到错误:UseMethod(“type”)中的错误:没有适用于“type”的适用方法应用于“c('tbl_df','tbl','data.frame')”类的对象。如果可能的话,我想知道如何让这两个选项起作用。此外,您对 DataCombine 包的想法将不胜感激。我以前没遇到过。

【问题讨论】:

  • 你能分享来自你实际df 的数据并显示它的预期输出吗?您还想只从DataCombine 包中获得答案还是对其他解决方案持开放态度?
  • @RonakShah,这是来自 Kaggle 的 515k 酒店评论,超过 515k 行和 17 列。但我觉得我提供的样本 df 足以代表我正在寻找的东西。数字列不是必需的,但强化了我原来是数据框而不是向量或列表的事实。我更新了问题以显示结果,这很好,我使用 DataCombine。我不需要这方面的帮助。我希望从 sapply 和 str_replace_all 中获得其他选项,但其他选项(我喜欢 dplyr)也很棒。另外,如果有人使用 DataCombine 以及他们对它的看法。

标签: r replace


【解决方案1】:

我这样做的两种方法是使用嵌套的 ifelse 语句或替换表,然后是 left_join()。

嵌套 ifelse 示例:您可以根据需要循环多次。

    df %>%
       mutate(col_with_text = ifelse(col_with_text == "Nothing", "None",
                                    ifelse(col_with_text == "nada", "None", NA)) 

表和左连接示例:

table_for_join <- data.frame(col_with_names = c('Nothing', 'no thing', 'nada', 'nuthin', 'not a thing', 'nothing', 'nothing', 'Nothing', 'nil'),
                             new_values = "None") # just made this one all the same for simplicity, but you can define this table however makes sense 

df %>%
  mutate(new_col = left_join(., table_for_join))

【讨论】:

    【解决方案2】:

    你可以试试这个方法

    df2 <- df %>% 
      mutate(words = str_replace_all(words, regex(" "), "")) %>% 
      mutate(words =  str_to_title(words, locale = "en")) %>% 
      mutate(words =  str_replace_all(words, regex("^Na.*|^Nu.*|^Nil.*|^Nota.*"), "Nothing"))
    df2
    #     words   number
    # 1 Nothing      1
    # 2 Nothing      2
    # 3 Nothing      3
    # 4 Nothing      4
    # 5 Nothing      5
    # 6 Nothing      6
    # 7 Nothing      7
    # 8 Nothing      8
    # 9 Nothing      9
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 2013-10-10
      • 2018-03-27
      • 1970-01-01
      相关资源
      最近更新 更多