Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a group of words from a character vector

Tags:

r

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?

like image 830
ATMA Avatar asked Oct 29 '13 19:10

ATMA


People also ask

How do I remove a string from a character vector 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.

How do you remove a character from a vector?

vector::clear() clear() removes all elements from vector and reducing it to size 0. erase() is used to remove specific elements from vector.


1 Answers

gsub(x = dat, pattern = paste(car, collapse = "|"), replacement = "")
[1] "Tony" "Dave" "Alex"
like image 172
TheComeOnMan Avatar answered Sep 27 '22 20:09

TheComeOnMan