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?
You can use sub
to replace a pattern within a string in R. Use a ^
at the start of your match pattern so that only strings starting with this pattern are replaced. Just replace with the empty string, ""
sub("^The Quick ", "", test_strings)
#> [1] "Brown Fox" "Yellow Fox" "The Slow Red Fox"
Alternately, use trimws
:
trimws(test_strings, whitespace = '^The Quick ')
#> [1] "Brown Fox" "Yellow Fox" "The Slow Red Fox"
Created on 2023-01-10 with reprex v2.0.2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.