Strings and Dates
String Cleanup
Slugs
Text data often needs a machine-friendly version. Base R string functions can normalize names.
Program
Play the script to lowercase a name, replace spaces, and add a file extension.
string_cleanup.R
Replay: real traced execution (multi-file project)
name <- "Ada Lovelace"
slug <- tolower(gsub(" ", "_", name))
label <- paste0(slug, ".txt")
cat(label, "\n", sep = "")
name ← Ada Lovelace
1name <- "Ada Lovelace"2slug <- tolower(gsub(" ", "_", name))values this stepAda Lovelacenameslug ← ada_lovelace
1name <- "Ada Lovelace"2slug <- tolower(gsub(" ", "_", name))3label <- paste0(slug, ".txt")values this stepada_lovelaceslugAda Lovelacenamelabel ← ada_lovelace.txt
2slug <- tolower(gsub(" ", "_", name))3label <- paste0(slug, ".txt")4cat(label, "\n", sep = "")values this stepada_lovelace.txtlabelada_lovelaceslugcat(label, " ", sep = "")
3label <- paste0(slug, ".txt")4cat(label, "\n", sep = "")outputada_lovelace.txtvalues this stepada_lovelace.txtlabel
Follow the Values
namestarts asAda Lovelace.gsub(" ", "_", name)changes the space to_.tolower(...)makes the slugada_lovelace.paste0(slug, ".txt")buildsada_lovelace.txt.- The script prints
ada_lovelace.txt. | step | value | | --- | --- | |name| Ada Lovelace | | aftergsub| Ada_Lovelace | |slug| ada_lovelace | |label| ada_lovelace.txt |
gsub
`gsub(" ", "_", name)` replaces every space with an underscore.
tolower
`tolower` converts text to lowercase.
paste0
`paste0` joins strings without inserting spaces.
Exercise: string_cleanup.R
Reproduce ada_lovelace.txt, then trace which step adds the .txt suffix.