对R中的字符串进行部分匹配,并获取匹配和不匹配的记录

对R中的字符串进行部分匹配,并获取匹配和不匹配的记录,r,string,R,String,我有一个名为mystring的对象,其中我有全长字符串,它们在另一个名为match.string的对象中部分匹配。我想使用match.string在mystring中设置诱饵,并找到完整长度的匹配字符串。我还需要在mystring中匹配和不匹配的字符串的记录 mystring<-c("the_dootle_doo_bottle-doo","no_cuddle-doo_do_bottle-coo","tape-it-ape-it","mac-chicken-no-good") match.s

我有一个名为
mystring
的对象,其中我有全长字符串,它们在另一个名为
match.string的对象中部分匹配。我想使用match.string在mystring中设置诱饵,并找到完整长度的匹配字符串。我还需要在
mystring
中匹配和不匹配的字符串的记录

mystring<-c("the_dootle_doo_bottle-doo","no_cuddle-doo_do_bottle-coo","tape-it-ape-it","mac-chicken-no-good")
match.string<-c("the_dootle","no_cuddle-doo","mac", "I-loathe-it","no-way")
另外,在结果中,我还希望看到match.strings中的字符串列表,这些字符串与mystring中的字符串匹配(
“the_dootle”、“no_cuddle-doo”、“mac”
)而不匹配(
“I-loata-it”、“no way”

l <- unlist(lapply(match.string, function(txt) mystring[grepl(txt, mystring)]))
要获取匹配/不匹配记录,您可以执行以下操作:

indx <- unlist(lapply(match.string, function(txt) grep(txt, mystring)))
使用此索引,您可以在
mystring
中获得匹配/不匹配的结果:

> indx
[1] 1 2 4
> mystring[indx]
[1] "the_dootle_doo_bottle-doo"   "no_cuddle-doo_do_bottle-coo" "mac-chicken-no-good"        
> mystring[-indx]
[1] "tape-it-ape-it"
要获取
match.string
的已找到项和未找到项,可以执行以下操作(如所建议):

您可以通过以下方式执行此操作:

l <- unlist(lapply(match.string, function(txt) mystring[grepl(txt, mystring)]))
要获取匹配/不匹配记录,您可以执行以下操作:

indx <- unlist(lapply(match.string, function(txt) grep(txt, mystring)))
使用此索引,您可以在
mystring
中获得匹配/不匹配的结果:

> indx
[1] 1 2 4
> mystring[indx]
[1] "the_dootle_doo_bottle-doo"   "no_cuddle-doo_do_bottle-coo" "mac-chicken-no-good"        
> mystring[-indx]
[1] "tape-it-ape-it"
要获取
match.string
的已找到项和未找到项,可以执行以下操作(如所建议):

试试看

mystring[pmatch(match.string,mystring)]

# [1] "the_dootle_doo_bottle-doo"   "no_cuddle-doo_do_bottle-coo" "mac-chicken-no-good"  NA    NA            
试试看

mystring[pmatch(match.string,mystring)]

# [1] "the_dootle_doo_bottle-doo"   "no_cuddle-doo_do_bottle-coo" "mac-chicken-no-good"  NA    NA            

谢谢,但是我如何获得匹配和不匹配的记录呢。这就是我遇到的问题。我实际上想要match.StringFind和not found的记录。为什么会出现此错误:unlist中的错误(as.matrix(lappy)(all.want.bam,function(txt)grep(txt),:在为函数“unlist”选择方法时计算参数“x”时出错:错误:(list)对象无法强制键入'double',我现在使用了另一种方法,请参阅更新。这样做有效吗?谢谢,但我如何获得匹配和未匹配的记录。这就是我遇到的问题。我实际上希望找到匹配和未找到匹配的记录。string为什么会出现此错误:unlist中的错误(as.matrix(lappy)(all.want.bam,函数(txt)grep(txt,:在为函数“unlist”选择方法时计算参数“x”时出错:错误:(list)无法强制对象键入“double”。我现在使用了另一个方法,请参阅更新。这是否有效?