I was recently reading a solution to an R4DS exercise. It includes the code:
library(stringr)
replacements <- c("A" = "a", "B" = "b", "C" = "c", "D" = "d", "E" = "e",
"F" = "f", "G" = "g", "H" = "h", "I" = "i", "J" = "j",
"K" = "k", "L" = "l", "M" = "m", "N" = "n", "O" = "o",
"P" = "p", "Q" = "q", "R" = "r", "S" = "s", "T" = "t",
"U" = "u", "V" = "v", "W" = "w", "X" = "x", "Y" = "y",
"Z" = "z")
lower_words <- str_replace_all(words, pattern = replacements)
head(lower_words)
and I found the construction of the replacements
vector particularly offensive. Nobody should have to do that much typing, particularly given that R has the vectors letters
and LETTERS
built-in.
Is there any way to automatically construct a vector like this? I tried to create it using expression objects, but I found that we cannot even run code as simple as quote("A" = "a")
because "A" = "a"
is not a syntactically valid expression. I also tried to create it using strings, e.g. some tricks using paste
, but those didn't work because we need the equals sign to not be a string. My nearest guess was substitute(c(a=b), list(a=LETTERS, b=letters))
, but the output is obviously incorrect.