如果一个字符串向量中的单词与另一字符串向量中的单词匹配,则用空格替换

时间:2019-02-19 15:07:54

标签: r

我试图在“ Cust.Name”中找到“ City”的任何匹配项。如果匹配,则用“ Cust.Name”中的空格替换“ City”的存在。因此,只会显示没有“城市”的“客户名称”。

Cust.Name <- as.data.frame(c("Eric Lee", "Mendham Middle School", "John Doe", "Johnson Elementary"))
colnames(Cust.Name) <- "Cust.Name"

City <- as.data.frame(c("Durham", "Mendham", "Elon", "Johnson"))
colnames(City) <- "City"

Customer = cbind(Cust.Name , City)
Customer$Cust.Name = as.character(Customer$Cust.Name)
Customer$City = as.character(Customer$City)

我已经尝试过了:

Customer$Cust.Name = sapply(gsub(pattern = Customer$City , replacement = '' , x = Customer$Cust.Name), function(x) x )

所需结果应为:

"Eric Lee" , "Middle School" , "John Doe" , "Elementary"

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

library(tidyverse)

cust_name <- c("Eric Lee", "Mendham Middle School", "John Doe", "Johnson Elementary")
city <- c("Durham", "Mendham", "Elon", "Johnson")

str_replace_all(cust_name, city, "") %>% str_squish()
# [1] "Eric Lee"      "Middle School" "John Doe"      "Elementary" 

以上所述仅在矢量成对运行时才有效-否则,您将需要paste(..., collapse = "|")城市。例如:

# Note the new order of `cust_name`
cust_name <- c("Eric Lee", "John Doe", "Mendham Middle School", "Johnson Elementary")
city <- c("Durham", "Mendham", "Elon", "Johnson")

str_replace_all(cust_name, paste(city, collapse = "|"), "") %>%
  str_squish()

答案 1 :(得分:0)

您可以使用gsub,即

gsub(paste(City$City, collapse = '|'), '', Cust.Name$Cust.Name)
#[1] "Eric Lee"       " Middle School" "John Doe"       " Elementary"