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?
Use gsub() function to remove a character from a string or text in R. This is an R base function that takes 3 arguments, first, the character to look for, second, the value to replace with, in our case we use blank string, and the third input string were to replace.
vector::clear() clear() removes all elements from vector and reducing it to size 0. erase() is used to remove specific elements from vector.
gsub(x = dat, pattern = paste(car, collapse = "|"), replacement = "")
[1] "Tony" "Dave" "Alex"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With