Search code examples
rstringvectorstring-matching

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.


Solution

  • 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