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!