Session Ready
Exercise

Replacing to tidy strings

You've seen one common strategy to pull variables out of strings is to split the string based on a pattern. Sometimes, it's easier to just replace the parts you don't want with an empty string "". This is also a common strategy to clean strings up, for example, to remove unwanted punctuation or white space.

In this exercise you'll pull out some numbers by replacing the part of the string that isn't a number, you'll also play with the format of some phone numbers. Pay close attention to the difference between str_replace() and str_replace_all().

Instructions 1/2
undefined XP
  • 1
    • Keep the numeric part of ids, by replacing "ID#: " with an empty string "".
    • Turn the ID strings to numbers using as.numeric(), assign the result to id_ints.
    • 2
      • Use str_replace() on phone_numbers to replace the "-" with a space, " ". Take a close look at the output, are there still some "-"s?
      • Repeat the previous task but now use str_replace_all(). Notice the difference, all the "-"s are replaced!
      • Reformat the phone numbers to use dots instead of dashes, i.e. in the format xxx.xxx.xxxx.