0

I have an assignment to "Write a function remove_digits that will remove all digits (i.e., 0 through 9) from all elements in a vector of strings." I tried doing this with a "while" loop:

strings <- vector(mode = "character")
remove_digits <- function(strings) {
  new_string <- strings
  i <- 0
  while (i < 10) {
    i_str <- toString(i)
    new_string <- str_remove(new_string, i_str)
    i <- i + 1
  }
  return(new_string)
}

However, my TA told me we're not supposed to be using "while"/"for" loops yet. All the answers I've found on Stack Overflow (like this one, which uses regex) are using tools that we haven't yet learned. I thought this would work:

remove_digits <- function(strings) {
  digits <- sapply(0:9, toString)
  strings <- lapply(strings, str_remove, digits)
  return(strings)
}

But that just makes a list of strings like this:

 [1] "1234c5678d9" "0234c5678d9" "0134c5678d9" "0124c5678d9" "0123c5678d9" "01234c678d9" "01234c578d9" "01234c568d9" "01234c567d9" "01234c5678d"

Also, I'm not sure if it's applicable here, but we've been learning stringr lately, so maybe I'm supposed to use one of those functions here? I couldn't figure out a way to do it, since I'm not really searching for specific patterns in the text, but hey. You never know.

If possible, I'd love a hint on how I could think about the problem in a different way, as opposed to just giving me the answer.

Thanks in advance!

  • I'm a little confused. You haven't learned (and therefore should not use?) regular expressions yet ... but you're using `stringr::str_replace`, which uses regular expressions. Are you supposed to be looking at individual characters and removing those from a set? – r2evans Apr 23 '20 at 03:30
  • @RonakShah, some believe that homework assignments on SO should not be given the "easy out" like that :-) – r2evans Apr 23 '20 at 03:31
  • 1
    @r2evans Ok..deleted the comment. Feel free to open the dupe link if you think that it gives the answer to OP directly. – Ronak Shah Apr 23 '20 at 03:35
  • Actually, r2evan's top comment was the correct answer, not the "duplicate" link. My question is quite different from that one. Besides, he didn't give me the answer - he just told me to check out `str_replace`. I figured out how to make it work in my situation on my own. – Molly Taylor Apr 24 '20 at 01:37

0 Answers0