In R remove all characters in string that is substring of other character

Viewed 58

This is a simple toy example. I would like to only keep the shortest sub-string. AB we keep and ABC can be excluded. BD and ADB we keep because there is no langer character that also has this pattern.

have <- c('AB', 'BD', 'ADB', 'ABC')
want <- c('AB', 'BD', 'ADB')

grepl is very useful here but I'm not sure how to make it computationally efficient.

1 Answers

Here is a base R approach:

have <- c('AB', 'BD', 'ADB', 'ABC')
keep <- sapply(have, function(x) grepl(paste0(have[!have %in% x], collapse="|"), x))
want <- have[!keep]
want

[1] "AB"  "BD"  "ADB"

The idea here is, for each entry in your input vector, to build a regex alternation consisting of the remaining terms. So, when sapply reaches the final value ABC, we form the following regex alternation:

AB|BD|ABD

Then, we use grepl to see if we can find any entry which is a substring of ABC. In this case, we can, using AB, so then we mark as true. Finally, we subset the input vector using this boolean vector.

Related