Skip to content

Instantly share code, notes, and snippets.

@DavisVaughan
Last active February 24, 2021 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavisVaughan/f41027c5334f7debc09fc606798e20ef to your computer and use it in GitHub Desktop.
Save DavisVaughan/f41027c5334f7debc09fc606798e20ef to your computer and use it in GitHub Desktop.
Subset for all except certain words / patterns using stringr?
library(stringr)
# I had something like this
bobs <- c("bob.txt", "bob.scn", "bob")
# I want to remove just the strings with "scn"
# Using: https://stackoverflow.com/questions/5556213/regex-to-match-everything-except-the-given-words-which-may-include-hyphens-dash
str_subset(bobs, "^(?:(?!scn).)*$")
#> [1] "bob.txt" "bob"
# Also just realizing I can do
bobs[!str_detect(bobs, "scn")]
#> [1] "bob.txt" "bob"
# With that in mind, I'd rather be able to do something like:
str_ignore <- function(string, pattern) {
string[!str_detect(string, pattern)]
}
str_ignore(bobs, "scn")
#> [1] "bob.txt" "bob"
str_ignore(bobs, "scn|txt")
#> [1] "bob"
# This is basically the opposite of what str_subset does right?
# Might be a useful extra function?
# Or is there an easier way with str_subset?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment