【问题标题】:Remove elements of a vector that are substrings of another删除一个向量的作为另一个子字符串的元素
【发布时间】:2015-10-18 19:14:58
【问题描述】:

有没有更好的方法来实现这一点?我想从这个向量中删除所有字符串,它们是其他元素的子字符串。

words = c("please can you", 
  "please can", 
  "can you", 
  "how did you", 
  "did you",
  "have you")
> words
[1] "please can you" "please can"     "can you"        "how did you"    "did you"        "have you"

library(data.table)
library(stringr)
dt = setDT(expand.grid(word1 = words, word2 = words, stringsAsFactors = FALSE))
dt[, found := str_detect(word1, word2)]
setdiff(words, dt[found == TRUE & word1 != word2, word2])
[1] "please can you" "how did you"    "have you" 

这行得通,但似乎有点矫枉过正,我很想知道一种更优雅的方法。

【问题讨论】:

  • CJdata.table 快得多 expand.grid
  • 只是想在这上面放点肉给任何跟进的人。 CJ 快得多。我将12431 行与15.69 字/行的平均值合并为一组195065 字,然后在user system elapsed 8.414 3.387 13.854 中通过system.time(dt <- setDT(expand.grid(word1 = words, word2 = words, stringsAsFactors = FALSE)))user system elapsed 0.932 0.365 1.320 中运行system.time(dt1 <- CJ(words,words,unique = TRUE))。数量级差异。
  • 太棒了,感谢基准测试

标签: r string


【解决方案1】:

words 中搜索words 的每个组件,保留那些出现一次的组件:

words[colSums(sapply(words, grepl, words, fixed = TRUE)) == 1]

给予:

[1] "please can you" "how did you"    "have you"   

【讨论】:

  • 这太棒了 - 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 2015-07-19
  • 2015-01-10
相关资源
最近更新 更多