Why does a named vector need to be unquoted when using `recode`?

Why does a named vector need to be unquoted when using recode?

char_vec <- sample(c("a", "b", "c"), 10, replace = TRUE)
level_key <- c(a = "apple", b = "banana", c = "carrot")
recode(char_vec, !!!level_key) # unquoted here

I'm not sure of the type of explanation you wish to have.
The short answer is that that was how the recode function was designed to work.
As a rule of thumb in programming, specific implementations based on strong assumptions are the easiest sorts of programs/functions to write. Providing more ways/idioms to use a function, and being more accomodating over param values/structures passed in might be 'nicer' for end users, but is harder for developers to do a good job and avoid bugs with.
the code for dplyr::recode is available getAnywhere(recode.character)

function (.x, ..., .default = NULL, .missing = NULL) 
    .x <- as.character(.x)
    values <- list2(...)
    if (!all(have_name(values))) {
        bad <- which(!have_name(values)) + 1
        bad_pos_args(bad, "must be named, not unnamed")
    n <- length(.x)
    template <- find_template(values, .default, .missing)
    out <- template[rep(NA_integer_, n)]
    replaced <- rep(FALSE, n)
    for (nm in names(values)) {
        out <- replace_with(out, .x == nm, values[[nm]], paste0("`", 
            nm, "`"))
        replaced[.x == nm] <- TRUE
    .default <- validate_recode_default(.default, .x, out, replaced)
    out <- replace_with(out, !replaced & !is.na(.x), .default, 
    out <- replace_with(out, is.na(.x), .missing, "`.missing`")

you can see that the values for the level_key part make assumptions. i.e. that they be collected into a list (list2()), that the results be fully named etc.

1 Like

THIS was the solution I was looking for, thank you and next time I'll be more specifc

happy to help :slight_smile:
I learned something myself , about the internals of recode, I wouldn't have thought to look otherwise !

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.