如何将命名向量或两个向量作为参数传递给dplyr :: recode

bio*_*iha 7 r dplyr recode

我想将一个命名向量或两个向量传递给dplyr :: recode.假设我有:

library(dplyr)
set.seed(1)
x <- c("customer", sample(c("a", "b", "c"), 10, replace = TRUE))
recode_tbl <- tibble(letter = letters[1:3], fruit = c("apple", "banana", "cranberry"))
Run Code Online (Sandbox Code Playgroud)

我想要做的是使用recode_tbl的列重新编码x,而不必手动指定对:

recode(x, a = "apple", b = "banana", c = "cranberry")
Run Code Online (Sandbox Code Playgroud)

就像是:

recode(x, as.name(recode_tbl$letter) = recode_tbl$fruit)
Run Code Online (Sandbox Code Playgroud)

这显然不起作用.我并不反对尝试NSE,但是如果有人能够得到足够的球,那就太棒了.

谢谢.

akr*_*run 7

我们可以做到这一点 base R

x1 <- unname(setNames(recode_tbl$fruit, recode_tbl$letter)[x])
x1[is.na(x1)] <- x[is.na(x1)]
Run Code Online (Sandbox Code Playgroud)

或者使用do.callrecode

do.call(dplyr::recode, c(list(x), setNames(recode_tbl$fruit, recode_tbl$letter)))
#[1] "customer"  "apple"     "banana"    "banana"    "cranberry" "apple"
#[8] "cranberry" "cranberry" "banana"    "banana"    "apple"   
Run Code Online (Sandbox Code Playgroud)

  • 尽管这个问题已经很老了:你可以通过使用 !!! 来绕过 do.call 操作员。所以这是最短的 recode 调用: `recode(x, !!!setNames(recode_tbl$fruit, recode_tbl$letter))` (2认同)