Removing a group of words from a character vector

Let's say that I have a character vector for random names. I also have another character vector with several cars, and I want to delete any incident of a car incident in the original vector.

So the vectors are given:

dat = c("Tonyhonda","DaveFord","Alextoyota") car = c("Honda","Ford","Toyota","honda","ford","toyota") 

I want to get something like below:

 dat = c("Tony","Dave","Alex") 

How to remove part of a string in R?

+8
r
source share
2 answers
 gsub(x = dat, pattern = paste(car, collapse = "|"), replacement = "") [1] "Tony" "Dave" "Alex" 
+15
source share

Just fill out the 42-comment above. Instead of using

 car = c("Honda","Ford","Toyota","honda","ford","toyota") 

You can simply use:

 carlist = c("Honda","Ford","Toyota") gsub(x = dat, pattern = paste(car, collapse = "|"), replacement = "", ignore.case = TRUE) [1] "Tony" "Dave" "Alex" 

This allows you to only put every word that you want to be excluded from the list once.

+1
source share

All Articles