识别R中字符向量中的模式实例

时间:2016-07-13 18:10:31

标签: r functional-programming pattern-matching

我试图在字符串向量中识别模式的所有实例。我正在看这样的事情:

    fruits <- c("Cherry", "Grape", "Orange", "Lemon")
    pattern <- c("Lemon", "Grape", "Cherry", "Grape")
    full <- sample(fruits, 1000, replace = TRUE)

我只想在pattern中找到full的每个实例。我内心的Java宝宝说要循环,这样的事可能吗?

    for(i in 1:(length(full)-length(pattern))) {
      if(full[i] == pattern[1]) {
        if(full[i+1] == pattern[2]) {
          ...

然后保存索引。但这对我来说似乎不是很有效或非常有效。这是要走的路,或者有人能指出我可以使这更方便/更快的功能或包的方向吗?

编辑: 抱歉,我不清楚,我需要知道patternfull开始的位置,即如果full中某处最终看起来像这样:

    ...
    [177] "Lemon"  "Grape " "Cherry" "Grape"  "Grape"  "Lemon"  "Cherry" "Grape"  "Lemon"  "Cherry" "Orange"
    ...

然后我有办法找到那个索引(177),因为模式(柠檬,葡萄,樱桃,葡萄)出现在那里并从那里开始。然后理想情况下,如果模式再次出现,我也知道,我需要能够找到{em> pattern的所有实例。

2 个答案:

答案 0 :(得分:2)

以下内容应该有效。

which(full %in% pattern)

答案 1 :(得分:0)

我并不完全清楚你在寻找什么,但是

l = apply(sapply(full, grepl, pattern), 1, function(x) { (1:length(full))[x] })
names(l) = pattern

将为您提供与pattern中元素长度相同的列表,并在full中查看pattern所在的位置。我使用grepl,因为pattern意味着字符串匹配给我,可能是

如果它不是部分字符串匹配,%in%肯定会更快。