0

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?

2
  • 2
    stringr::str_remove(test_strings, "^The Quick ") adding the ^ the the start of the pattern means "only look at the beginning" Commented Jan 10, 2023 at 20:42
  • Ahhhhhh I think this works. The ^ is the key part here - I was unaware of this trick. Thank you. Much nicer. Commented Jan 10, 2023 at 20:44

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.