It would be really convenient if recode could accept a named list as an argument instead of having to specify each of the input parameters.
Currently to use the function you have to do something like
x <- c( "a" , "b" , "c")
recode( x , a = "1" , b = "2" , c = "3")
I propose that the following be valid
MAP <- list(
a = "1" ,
b = "2" ,
c = "3"
)
recode( x , MAP )
This allows for standardized maps to be setup and used across a project which is useful when you are dealing with short variable names or coded parameter terms which need to be transformed into more wordy labels later on.
Part of #2477
@hadley Has this been implemented?
I've been trying to use named lists in dplyr::recode() but it doesn't seem to work.
I suppose I'll stick with the tried and true left_join lookup table for now.
x <- c("a", "b", "c")
MAP <- list(a = "1", b = "2", c = "3")
dplyr::recode(x, MAP)
#> Error: Argument 2 must be named, not unnamed
Here is my left_join solution
x <- c("a", "b", "c")
MAP <- list(a = "1", b = "2", c = "3")
dplyr::recode(x, MAP)
#> Error: Argument 2 must be named, not unnamed
x_lj <- tibble::tibble(x = x)
MAP_lj <- dplyr::bind_cols(x = names(MAP), y = as.character(MAP))
dplyr::left_join(x_lj, MAP_lj, by = "x")
#> # A tibble: 3 x 2
#> x y
#> <chr> <chr>
#> 1 a 1
#> 2 b 2
#> 3 c 3
@CG1122 I figured it out via http://dplyr.tidyverse.org/articles/programming.html:
x <- c("a", "b", "c")
MAP <- list(a = "1", b = "2", c = "3")
dplyr::recode(x, !!!MAP)
#> [1] "1" "2" "3"
Thanks @hadley @lionel- and tidyverse !
I was about to suggest a recode_ function that does what @ahcyip suggested. Can that example or one largely similar be added to the documentation, please?
Most helpful comment
@CG1122 I figured it out via http://dplyr.tidyverse.org/articles/programming.html:
Thanks @hadley @lionel- and tidyverse !