首页 > 解决方案 > Replace words from one vector of strings with blanks if they match in another vector of strings

问题描述

I am trying to find any matching of "City" inside "Cust.Name". If there is a match, replace the presence of "City" with a blank in "Cust.Name". Therefore only "Cust.Name" without "City" will show up.

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)

I have tried this:

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

Desired results should be:

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

Any help would be greatly appreciated.

标签: r

解决方案


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()

推荐阅读