Hello RStudio Cognoscenti,
I'm trying to implement quasi-quotation with dplyr::recode_factor()
. I would like to dynamically re-map (recode) the individual values AND re-level the factor levels. In the reprex
below the original values are [A, B, C]
s and the levels are A B C
(default). I would like to map: A -> Amigo, B -> Be, and C -> Cool
as well as reorder the factor levels to: Be Cool Amigo
. Using dplyr::recode()
works with quasi-quotation, but it ignores the re-leveling defined by level_key
. However, using quasi-quotation with dplyr::recode_factor
breaks. I can achieve the re-leveling using recode_factor()
by hard coding the arguments, however this will not work for the implementation I have in mind. Am I using the (!!!) incorrectly? Is this a bug? I do realize I could solve this in two steps. Apologies in advance if this has already been addressed and I've missed it.
Thank you,
Stu
library(magrittr)
library(dplyr)
set.seed(100)
x <- sample(head(LETTERS, 3), 10, replace = TRUE) %>% factor
x
level_key <- list("Be", "Cool", "Amigo") %>% set_names(c("B", "C", "A")) # set factor re-level
level_key
dplyr::recode(x, !!!level_key) # no re-leveling; desired B C A :(
dplyr::recode_factor(x, B = "Be", C = "Cool", A = "Amigo") # correct levels; but not quasi-quotation :(
dplyr::recode_factor(x, !!!level_key) # errors out :(