Search code examples
rsubsetgrepl

How can I remove all elements from a vector that matches a pattern?


ncvars = c("prate", "arate", "wpd", "Atm1", "Atm2", "area", "fC", "bas__1", "bas__asssaa", "bas__Clow", "bas__g2333e", "baser__arge", "bas__Aow", "bas__Aass")   

Now, I want to remove all elements that are

  • exactly the name area
  • matches this string bas__

How can I do this?


Trial

patterns <- c("bas__", "area")
ncvars %>%
  filter(.,grepl(paste(patterns, collapse="|")))

Solution

  • You can just negate grepl with ! and also to match exactly, you need ^..$ anchors to match the start(^) and end($) of string:

    ncvars[!grepl('^area$|bas__', ncvars)]
    

    ncvars
    # [1] "prate"       "arate"       "wpd"         "Atm1"        "Atm2"        "area"        "fC"          "bas__1"     
    # [9] "bas__asssaa" "bas__Clow"   "bas__g2333e" "baser__arge" "bas__Aow"    "bas__Aass"  
    ncvars[!grepl('^area$|bas__', ncvars)]
    # [1] "prate"       "arate"       "wpd"         "Atm1"        "Atm2"        "fC"          "baser__arge"