如何从与模式匹配的向量中删除所有元素?

时间:2017-10-18 18:07:05

标签: r grep subset grepl

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

现在,我想删除所有

元素
  • 完全是名称area
  • 匹配此字符串bas__

我该怎么做?

试验

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

2 个答案:

答案 0 :(得分:4)

您可以使用grepl取消!,并且要完全匹配,您需要^..$个锚点来匹配开头(^)和结束($ })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"

答案 1 :(得分:1)

tidyverse解决方案:

library(stringr)
str_replace(ncvars, pattern = "^area$|^bas__", replacement = "")
# [1] "prate"       "arate"       "wpd"         "Atm1"       
# [5] "Atm2"        ""            "fC"          "1"          
# [9] "asssaa"      "Clow"        "g2333e"      "baser__arge"
# [13] "Aow"         "Aass"