R - 用多个 ID 替换多个模式

R - Replace multiple patterns with multiple ids

其他帖子已经部分解决了这个问题,但不幸的是,我无法 运行 正确地做到这一点。

我有一个充满文本的数据框,我想用唯一的名称替换某些单词。

所以,如果我们看到下面的 table,我想用“Fruit”这个词替换每个“Banana Apple Tomato”这个词(Fruit 这个词可以出现多次,也就是说行) 我还想用“动物”一词代替“Cod Pork Beef”

我有一个完成此映射的完整 excel 文件。 excel 文件有两列。 在 A 列中,我们有唯一的名称(如 Fruit 和 Animals)。在 B 列上,我们有要在文本中替换的词(如香蕉、苹果、番茄)。

我想出的代码是:

hous <- read.table(header = TRUE, 
                   stringsAsFactors = FALSE, 
                   text="HouseType HouseTypeNo
'Banana Apple Tomato Honey' 'Onion Garlic Pepper Sugar'
'Cod Pork Beef' 'Mushrooms Soya Eggs' ")

maps <- read.table(header = TRUE, 
                           stringsAsFactors = FALSE, 
                           text="UniqueID Names
'Fruit' 'Banana'
'Fruit' 'Apple'
'Fruit' 'Tomato'
'Animals' 'Cod'
'Animals' 'Pork'
'Animals' 'Beef'")

hous %>% str_replace_all( pattern = maps$Names, replacement = maps$UniqueID)
*#Warning message:
In stri_replace_all_regex(string, pattern, fix_replacement(replacement),  :
  argument is not an atomic vector; coercing*

我无法让它工作。 我基本上只想查找某些单词,并用一些独特的 ID 替换它们。 听起来不复杂,但我做不到运行。

简单说明几点:在我的真实数据集中我有几千个单词和ID。我在其他示例中看到人们手写他们的 ID、模式和替换。就我而言,这不适用。

最终输出将是这样的:

hous <- read.table(header = TRUE, 
                   stringsAsFactors = FALSE, 
                   text="HouseType HouseTypeNo
'Fruit Fruit Fruit Honey' 'Onion Garlic Pepper Sugar'
'Animal Animal Animal' 'Mushrooms Soya Eggs' ")

感谢任何帮助。

此致

您可以创建命名列表并使用它来替换 str_replace_all 中的值:

hous$HouseType <- stringr::str_replace_all(hous$HouseType, 
                            setNames(maps$UniqueID, maps$Names))
hous

#                HouseType               HouseTypeNo
#1 Fruit Fruit Fruit Honey Onion Garlic Pepper Sugar
#2 Animals Animals Animals       Mushrooms Soya Eggs