Search code examples
rends-with

R equivalent of endsWith to check against a list of strings


I am attempting to check whether values in a column of a data frame end with any value from a predefined list of strings contained in a vector. I understand it is possible to check against a single string using endsWith, but I have not found a way of using this to check against a list of strings.

x <- c(" 2", " 3", " II", " III")
title <- c("a 2", "adbs", "ddig", "difo 3", "fgij III", "sdgoij")
endsWith(title, x)

I would not expect this code to do what I want it to, but what I am looking for is code that gives the following output using the above data. TRUE FALSE FALSE TRUE TRUE FALSE


Solution

  • An option is to loop through the 'x', apply endsWith and Reduce the list of vectors to a single logical vector

    Reduce(`|`, lapply(x, function(y) endsWith(title, y)))
    #[1]  TRUE FALSE FALSE  TRUE  TRUE FALSE
    

    Another option is grepl by pasteing the elements of 'x' to a single string with delimiter (|) and the metacharacter ($) at the end to specify the end of string

    pat <- paste0("(", paste(x, collapse = "|"), ")$")
    grepl(pat, title)
    #[1]  TRUE FALSE FALSE  TRUE  TRUE FALSE