R 如果一个字符串向量中的单词与另一个字符串向量中的单词匹配,则将其替换为空格
我试图在“客户名称”中找到任何匹配的“城市”。如果存在匹配项,则将“客户名称”中的“城市”替换为空白。因此,将只显示“Cust.Name”,而不显示“City”R 如果一个字符串向量中的单词与另一个字符串向量中的单词匹配,则将其替换为空格,r,R,我试图在“客户名称”中找到任何匹配的“城市”。如果存在匹配项,则将“客户名称”中的“城市”替换为空白。因此,将只显示“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
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)
预期结果应为:
"Eric Lee" , "Middle School" , "John Doe" , "Elementary"
非常感谢您的帮助。您可以使用
gsub
,即
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"
gsub(paste(City$City, collapse = '|'), '', Cust.Name$Cust.Name)
#[1] "Eric Lee" " Middle School" "John Doe" " Elementary"
谢谢,杰森,是的,我需要他们在这种情况下是成对的。这个解决方案非常有效!我需要字符串成对出现在这个案例中。你是什么意思?我得到了你的期望输出
# 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()
gsub(paste(City$City, collapse = '|'), '', Cust.Name$Cust.Name)
#[1] "Eric Lee" " Middle School" "John Doe" " Elementary"