Search code examples
rdplyrrecode

Dpylr's recode function multiple-to-1 R


I would like an easier way to recode vectors. Specifically I'm wondering if there is a way to pass vectors to a function like dplyr's recode. I understand the basics of quasiquotation but don't quite get how to incorporate the =.

library(tidyverse)

vec1 <- rep(LETTERS[1:7],7)

#standard way
vec2 <- recode(vec1, 
               "A" = "Value1",
               "B" = "Value2",
               "C" = "Value3",
               "D" = "Value4",
               "E" = "Value5",
               "F" = "Value6",
               "G" = "Value7"
               )

vec3 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value1",
               "C" = "Value2",
               "D" = "Value2",
               .default = "Value other"
               )

I'd like to do the following

vec3 <- some.function(vec1,
               c("A", "B") = "Value1",
               c("C", "D") = "Value2",
               .default = "Value other"
               )

I have a solution but can't figure out how to incorporate a function with ... and =

do.call(dplyr::recode, 
        c(list(vec1), 
        setNames(rep("Value1",length(val1)), val1), 
        setNames(rep("Value2",length(val2)), val2)))

I also have figured out a way to pass two vectors and rename all the variables.

recode.by.vectors <- function(x, current.names, new.names){
  do.call(dplyr::recode, c(list(x), setNames(new.names, current.names)))
}

Lastly, I'm aware of a base solution.

vec3 <- vec1
val1 <- c("A", "B")
val2 <- c("C", "D")
vec3[vec1 %in% val1] <- "Value1"
vec3[vec1 %in% val2] <- "Value2"
vec3[!vec1 %in% c(val1,val1)] <- "Value other"

but am unaware to how in incorporate the assignment carried out here into a function.


Solution

  • We can use case_when from the dplyr package.

    library(dplyr)
    
    vec1 <- rep(LETTERS[1:7],7)
    
    vec2 <- case_when(
        vec1 %in% c("A", "B")    ~ "Value1",
        vec1 %in% c("C", "D")    ~ "Value2",
        TRUE                     ~ "Value other"
      ) 
    head(vec2)
    # [1] "Value1"      "Value1"      "Value2"      "Value2"      "Value other" "Value other"