r - 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.
解决方案
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()
推荐阅读
- makefile - 问题:在 Git 中切换分支后重建整个项目
- google-app-engine - 为 PHP7.2 创建 Google Cloud Storage 上传 URL
- r - 在 R 中,predict() 函数和 model$predicted 值有什么区别?
- python - LinkedList - 在不插入的节点之间插入
- android - 中心android滚动div垂直框
- java - Spring Cloud Stream 向 Kafka 主题发送数据失败
- ios - 从 xib IBOutlets nil Swift 加载 UIViewController
- javascript - 如何在 html 表格中创建行
- c# - 实体框架,ASP.NET Identity 隐藏连接字符串?
- functional-programming - 在方案中随机取元素组