Search code examples
rtidyverserecode

How to use the same R recode function on multiple variables without coding each?


From the recode examples, what if I have two variables where I want to apply the same recode?

factor_vec1 <- factor(c("a", "b", "c"))
factor_vec2 <- factor(c("a", "d", "f"))

How can I recode the same answer without writing a recode for each factor_vec? These don't work, do I need to learn how to use purrr to do it, or is there another way?

Output 1: recode(c(factor_vec1, factor_vec2), a = "Apple")
Output 2: recode(c(factor_vec2, factor_vec2), a = "Apple", b = 
"Banana")

Solution

  • Use lists to hold multiple vectors and then you can apply same function using lapply/map.

    library(dplyr)
    list_fac <- lst(factor_vec1, factor_vec2)
    list_fac <- purrr::map(list_fac, recode, a = "Apple", b = "Banana")
    

    You can keep the vectors in list itself (which is better) or get the changed vectors in global environment using list2env.

    list2env(list_fac, .GlobalEnv)