grep using a character vector with multiple patterns

前端 未结 10 2330
猫巷女王i
猫巷女王i 2020-11-22 04:29

I am trying to use grep to test whether a vector of strings are present in an another vector or not, and to output the values that are present (the matching pat

10条回答
  •  逝去的感伤
    2020-11-22 05:33

    Based on Brian Digg's post, here are two helpful functions for filtering lists:

    #Returns all items in a list that are not contained in toMatch
    #toMatch can be a single item or a list of items
    exclude <- function (theList, toMatch){
      return(setdiff(theList,include(theList,toMatch)))
    }
    
    #Returns all items in a list that ARE contained in toMatch
    #toMatch can be a single item or a list of items
    include <- function (theList, toMatch){
      matches <- unique (grep(paste(toMatch,collapse="|"), 
                              theList, value=TRUE))
      return(matches)
    }
    

提交回复
热议问题