R 从相似字符串的向量中获取唯一字符串

R 从相似字符串的向量中获取唯一字符串,r,string,unique,R,String,Unique,我不太知道如何表达这个问题。我刚刚开始写一堆推文,我做了一些基本的清理,现在一些推文看起来像: x <- c("stackoverflow is a great site", "stackoverflow is a great si", "stackoverflow is a great", "omg it is friday and so sunny", "omg it is friday and so", "arggh how annoying") 因为所有其他的都是上述内容的重复。

我不太知道如何表达这个问题。我刚刚开始写一堆推文,我做了一些基本的清理,现在一些推文看起来像:

x <- c("stackoverflow is a great site",
"stackoverflow is a great si",
"stackoverflow is a great",
"omg it is friday and so sunny",
"omg it is friday and so",
"arggh how annoying")
因为所有其他的都是上述内容的重复。我试过使用
unique()
函数,但它不会返回我想要的结果,因为它试图匹配字符串的整个长度。有什么建议吗

我正在Mac OSX 10.7上使用R版本3.1.1

谢谢

以下是我的尝试:

library(stringr)
x[!sapply(seq_along(x), function(i) any(str_detect(x[-i], x[i])))]
[1] "stackoverflow is a great site" "omg it is friday and so sunny" "arggh how annoying" 

基本上,我排除了那些已经包含在任何其他字符串中的字符串。这可能与您描述的有所不同,但大致相同,而且非常简单。

这是另一种选择。我已将一个字符串添加到示例数据中

x <- c("stackoverflow is a great site",
"stackoverflow is a great si",
"stackoverflow is a great",
"stackoverflow is an OK site",
"omg it is friday and so sunny",
"omg it is friday and so",
"arggh how annoying")

Filter(function(y) {
    x2 <- sapply(setdiff(x, y), substr, start=1, stop=nchar(y))
    ! duplicated(c(y, x2), fromLast=TRUE)[1]
}, x)


# [1] "stackoverflow is a great site" "stackoverflow is an OK site"   "omg it is friday and so sunny" [4] "arggh how annoying"  

x@tonytonov解决方案很好,但我建议使用:)


stringi谢谢Matthew我认为它工作得很好它看起来很复杂我不明白那里发生了什么你怎么让它不去处理
stackoverflow是一个很棒的站点
stackoverflow是一个不错的站点
?对不起,谢谢。我误解了你的问题。所以你只想匹配第一个单词?不不不不,你没有误解它工作得很好。我的意思是,你如何让它区分
stackoverflow是一个很棒的站点
stackoverflow是一个不错的站点?
只是想知道你的代码中发生了什么,但它确实解决了问题。这个想法是针对每个人的字符串,将所有其他字符串收缩到相同长度。如果存在重复项,则您知道存在当前字符串的较长版本,并拒绝当前字符串。如果没有重复的字符串,那么当前字符串是最长的,因此您接受该字符串。感谢tony,它似乎可以工作,但对于较短的字符串,我的向量有大约1000个字符串,它将它们减少到650个。我不认为有那么多的副本需要剥离,但我必须手动检查以获得一个想法。您可以使用
排序(x[sapply(seq_沿着(x),函数(I)any(str_detect(x[-I],x[I]))查看这些副本)
。看起来我有很多复制品。你是对的,谢谢这很有效,能够看到它过滤掉的东西很酷。谢谢
x <- c("stackoverflow is a great site",
"stackoverflow is a great si",
"stackoverflow is a great",
"stackoverflow is an OK site",
"omg it is friday and so sunny",
"omg it is friday and so",
"arggh how annoying")

Filter(function(y) {
    x2 <- sapply(setdiff(x, y), substr, start=1, stop=nchar(y))
    ! duplicated(c(y, x2), fromLast=TRUE)[1]
}, x)


# [1] "stackoverflow is a great site" "stackoverflow is an OK site"   "omg it is friday and so sunny" [4] "arggh how annoying"  
stringi <- function(x){
  x[!sapply(seq_along(x), function(i) any(stri_detect_fixed(x[-i], x[i])))]
}

stringr <- function(x){
  x[!sapply(seq_along(x), function(i) any(str_detect(x[-i], x[i])))]
}

require(microbenchmark)
microbenchmark(stringi(x), stringr(x))
Unit: microseconds
       expr     min       lq   median       uq      max neval
 stringi(x)  52.482  58.1760  64.3275  71.9630  120.374   100
 stringr(x) 538.482 551.0485 564.3445 602.7095 1736.601   100