I need to be able to test if certain words appear at the start of a character vector. I've written a function which seems to work:
remove_from_front <- function(my_str, my_prefix) {
remove_from_front <- ifelse(startsWith(my_str, my_prefix),
substr(my_str, nchar(my_prefix) + 1, nchar(my_str)),
my_str)
remove_from_front
}
test_strings <- c("The Quick Brown Fox",
"The Quick Yellow Fox",
"The Slow Red Fox")
remove_from_front(test_strings, "The Quick ")
This looks for "The Quick " at the start of a string, and removes it if it finds it (and does nothing if it doesn't find it).
I'm wondering if there's some more concise way to do it using some existing R functionality - can anyone advise please?
stringr::str_remove(test_strings, "^The Quick ")adding the ^ the the start of the pattern means "only look at the beginning"