如何从匹配模式的向量中删除所有元素?
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")
现在,我想删除所有
- 正是名字
area
- 匹配这个字符串
bas__
我该怎么做?
试用
patterns <- c("bas__", "area")
ncvars %>%
filter(.,grepl(paste(patterns, collapse="|")))
你可以用 !
否定 grepl
并且要精确匹配,你需要 ^..$
锚来匹配开始(^
)和结束($
) 的字符串:
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"
一个tidyverse
解决方案:
library(stringr)
stringr::str_subset(ncvars, pattern = "^area$|^bas__", negate = TRUE)
[1] "prate" "arate" "wpd" "Atm1" "Atm2" "fC" "baser__arge"
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="|")))
你可以用 !
否定 grepl
并且要精确匹配,你需要 ^..$
锚来匹配开始(^
)和结束($
) 的字符串:
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"
一个tidyverse
解决方案:
library(stringr)
stringr::str_subset(ncvars, pattern = "^area$|^bas__", negate = TRUE)
[1] "prate" "arate" "wpd" "Atm1" "Atm2" "fC" "baser__arge"