使用元字符在grep中创建动态搜索字符串

时间:2016-03-25 03:30:05

标签: r string search grep metacharacters

您好我是R的新手我需要一个动态搜索字符串来运行一些单元格数组,寻找返回匹配存在的单元格子集的匹配项。

{
> somecellarray[]
the     to     and      a     of      i     in     is    for   that 
798691 481789 413651 408492 342748 314606 277411 192607 192076 181179
}

此直接表达式有效,在这种情况下,“th”出现在单元格名称的开头,因此请使用搜索表达式“^ th”。

{
    somecellarray[grep("^th",names(somecellarray))]


returns 
the    that 
798691 181179 
}

现在我想在一个自动循环中运行它,搜索字符串可以改变,所以我创建了这个测试。

{  
    searchstr <- "th"# just a test string
    #Now I create a search expression using cat() from searchstr
    searchexpr <- cat(c("\"^",searchstr,"\""),sep="") #....ie   searchexpr="^th"
    # then I use this with grep()
    somecellarray[grep(searchexpr,names(somecellarray))]

    Returns the following
    named numeric(0) 
    Warning message:
    In grep(somecellarray, names(somecellarray)) :
    argument 'pattern' has length > 1 and only the first element will be used
}

我不知道为什么会收到这个错误,我错过了什么?

感谢

0 个答案:

没有答案