ag14
ag14

Reputation: 867

In R, how can I search for the character vector element that is contained in a specific string?

I have a character vector element in R akin to:

[1] Deer  giraffe  hippopotamus lion       

and a string such as

a <- "ogiraffeps"

How can I find the index of the element in the character vector which has the pattern contained in my string? I want to be able to do this without looping through the character vector

I am new to R, but it seems that grep can't handle this as it always uses a single string (the pattern) to see if it is contained in a character vector. However, what I want to do is to find an element of the character vector that is contained in the string.

Upvotes: 3

Views: 11941

Answers (1)

Scarabee
Scarabee

Reputation: 5704

stringr::str_detect is vectorised over the pattern:

library(stringr)
u <- c("Deer", "giraffe", "hippopotamus", "lion")
a <- "ogiraffeps"

str_detect(a, u)
# [1] FALSE  TRUE FALSE FALSE

Thus you can do:

match(1, str_detect(a, u))
# [1] 2

Upvotes: 6

Related Questions