Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a substring exists in each element of a character vector?

I have a vector of names and a single city string. I want to test whether the city is a part of each element in the name vector. However, using grepl(city, name) doesn't work as the city doesn't appear exactly as it is in the name.

Here's an example of my data:

name <- c("Business Applications for New York", "Proprietors' Farm Income in New York", "Farm Business")
city <- "New York NY"

The desired output is the Boolean vector: c(TRUE, TRUE, FALSE)

How can I efficiently check if the city is part of each element in the name vector in R? Any suggestions or code examples would be greatly appreciated. Thank you!

like image 920
Joe94 Avatar asked Oct 16 '25 21:10

Joe94


1 Answers

You can try agrepl.

> agrepl(city, name, max.distance=3, ignore.case=TRUE, fixed=TRUE)
[1]  TRUE  TRUE FALSE
like image 164
jay.sf Avatar answered Oct 19 '25 13:10

jay.sf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!