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 = "")
  1. name ← Ada Lovelace

    1name <- "Ada Lovelace"2slug <- tolower(gsub(" ", "_", name))
    values this stepAda Lovelacename
  2. slug ← ada_lovelace

    1name <- "Ada Lovelace"2slug <- tolower(gsub(" ", "_", name))3label <- paste0(slug, ".txt")
    values this stepada_lovelaceslugAda Lovelacename
  3. label ← ada_lovelace.txt

    2slug <- tolower(gsub(" ", "_", name))3label <- paste0(slug, ".txt")4cat(label, "\n", sep = "")
    values this stepada_lovelace.txtlabelada_lovelaceslug
  4. cat(label, " ", sep = "")

    3label <- paste0(slug, ".txt")4cat(label, "\n", sep = "")
    outputada_lovelace.txt
    values this stepada_lovelace.txtlabel

Follow the Values

  1. name starts as Ada Lovelace.
  2. gsub(" ", "_", name) changes the space to _.
  3. tolower(...) makes the slug ada_lovelace.
  4. paste0(slug, ".txt") builds ada_lovelace.txt.
  5. The script prints ada_lovelace.txt. | step | value | | --- | --- | | name | Ada Lovelace | | after gsub | 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.