Last active
February 24, 2021 13:48
-
-
Save DavisVaughan/f41027c5334f7debc09fc606798e20ef to your computer and use it in GitHub Desktop.
Subset for all except certain words / patterns using stringr?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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