[英]In R remove all characters in string that is substring of other character
This is a simple toy example.这是一个简单的玩具示例。 I would like to only keep the shortest sub-string.
我只想保留最短的子字符串。 AB we keep and ABC can be excluded.
AB 我们保留而 ABC 可以排除。 BD and ADB we keep because there is no langer character that also has this pattern.
我们保留 BD 和 ADB,因为没有 langer 字符也具有这种模式。
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. grepl 在这里非常有用,但我不确定如何使其具有计算效率。
Here is a base R approach:这是一个基本的R方法:
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:因此,当
sapply
达到最终值ABC
,我们形成以下正则表达式交替:
AB|BD|ABD
Then, we use grepl
to see if we can find any entry which is a substring of ABC
.然后,我们使用
grepl
来查看是否可以找到任何属于ABC
子字符串的条目。 In this case, we can, using AB
, so then we mark as true.在这种情况下,我们可以使用
AB
,然后我们将其标记为 true。 Finally, we subset the input vector using this boolean vector.最后,我们使用这个布尔向量对输入向量进行子集化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.