Reputation: 1466
Let's say that I have a character vector of random names. I also have another character vector with a number of car makes and I want to remove any occurrence of a car incident in the original vector.
So given the vectors:
dat = c("Tonyhonda","DaveFord","Alextoyota")
car = c("Honda","Ford","Toyota","honda","ford","toyota")
I want to end up with something like below:
dat = c("Tony","Dave","Alex")
How can I remove part of a string in R?
Upvotes: 8
Views: 4493
Reputation: 2552
Just formalizing 42-'s comment above. Rather than using
car = c("Honda","Ford","Toyota","honda","ford","toyota")
You can just use:
carlist = c("Honda","Ford","Toyota")
gsub(x = dat, pattern = paste(car, collapse = "|"), replacement = "", ignore.case = TRUE)
[1] "Tony" "Dave" "Alex"
That allows you to only put each word you want to exclude in the list one time.
Upvotes: 1
Reputation: 12905
gsub(x = dat, pattern = paste(car, collapse = "|"), replacement = "")
[1] "Tony" "Dave" "Alex"
Upvotes: 17