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

94 Views Asked by At

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!

1

There are 1 best solutions below

0
jay.sf On

You can try agrepl.

> agrepl(city, name, max.distance=3, ignore.case=TRUE, fixed=TRUE)
[1]  TRUE  TRUE FALSE