以相同的顺序将模式的所有元素与向量匹配 [英] Match all elements of a pattern with a vector and in the same order

查看:41
本文介绍了以相同的顺序将模式的所有元素与向量匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个函数 yes.seq,它接受两个参数,一个模式 pat 和数据 dat.该函数查找数据中是否存在相同序列中的模式

I created a function yes.seq that takes two arguments, a pattern pat and data dat. The function looks for the presence of a pattern in the data and in the same sequence

例如

dat <- letters[1:10]
dat
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
pat <- c('a',"c","g")
 
yes.seq(pat = pat,dat = dat)
# [1] TRUE

因为这个序列在模式中的顺序相同

because this sequence is in the pattern and in the same order

a"b""c""d"e"f""g""h"我"j"

"a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

例如,如果'dat'被反转,那么我们得到FALSE:

If, for example, 'dat' is reversed, then we get FALSE:

yes.seq(pat = pat, dat = rev(dat))
# [1] FALSE

这是我的功能

yes.seq <- function(pat , dat){  
  lv <- rep(F,length(pat))
  k <- 1     
  for(i in 1:length(dat)){        
            if(dat[i] == pat[k]) 
              {
              lv[k] <- TRUE
              k <- k+1 
              }       
    if(k==length(pat)+1) break
  }
  return(  all(lv)   )
}

有没有更有效的解决方案,这个功能对我来说太慢了

Are there any more efficient solutions, this function is too slow for me

推荐答案

我们可以粘贴它们并使用 grepl

grepl(paste(pat, collapse=".*"), paste(dat, collapse=""))
#[1] TRUE

str_detect

library(stringr)
str_detect(paste(dat, collapse=""), paste(pat, collapse=".*"))
#[1] TRUE

这篇关于以相同的顺序将模式的所有元素与向量匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆