"A" = "a"、"B" = "b" 等形式的表达式如何从 LETTERS 和字母自动构建?

How can expressions of the form "A" = "a", "B" = "b", etc be constructed automatically from LETTERS and letters?

我最近在阅读 a solution to an R4DS exercise。它包括代码:

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)

我发现 replacements 向量的构造特别令人反感。没有人应该做那么多输入,特别是考虑到 R 有向量 lettersLETTERS 内置。

有什么方法可以自动构建这样的向量吗? 我尝试使用表达式对象来创建它,但我发现我们甚至不能 运行 代码如下像 quote("A" = "a") 一样简单,因为 "A" = "a" 不是语法上有效的表达式。我还尝试使用字符串创建它,例如一些使用 paste 的技巧,但这些技巧不起作用,因为我们需要等号不是字符串。我最接近的猜测是 substitute(c(a=b), list(a=LETTERS, b=letters)),但输出显然不正确。

letters/LETTERS,用

replacements <- setNames(letters, LETTERS)

另一种选择,但效率不如

> sapply(LETTERS, gsub, pattern = "(.*)", replacement = "\L\1", perl = TRUE)
  A   B   C   D   E   F   G   H   I   J   K   L   M   N   O   P   Q   R   S   T
"a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t"
  U   V   W   X   Y   Z
"u" "v" "w" "x" "y" "z"

或(感谢@akrun 的评论)

> sapply(letters, tolower)
  a   b   c   d   e   f   g   h   i   j   k   l   m   n   o   p   q   r   s   t
"a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t"
  u   v   w   x   y   z
"u" "v" "w" "x" "y" "z"

我认为这也行得通:

x <- LETTERS; names(x) <- letters

实际上,这正是 setNames 所做的。