7

Is there a way to use the recode function of dpylr together with a lookup table (data.frame or list)?

What I would like to have would look something like this:

# Recode values with list of named arguments
data <- sample(c("a", "b", "c", "d"), 10, replace = T) 
lookup <- list(a = "Apple", b = "Pear") 
dplyr::recode(data, lookup)

I found the mapvalues and revalue functions from the plyr package. Combining them is possible as explained here. However, I am wondering whether something similar is possible with dplyr only.

Community
  • 1
  • 1
Bushroot
  • 259
  • 1
  • 13

3 Answers3

5

We can use base R

v1 <- unlist(lookup)[data]
ifelse(is.na(v1), data, v1)
akrun
  • 874,273
  • 37
  • 540
  • 662
5
do.call(dplyr::recode, c(list(data), lookup))
[1] "Pear" "c"    "d"    "c"    "Pear" "Pear" "d"    "c"    "d"    "c"
Axeman
  • 32,068
  • 8
  • 81
  • 94
5

It works like this:

dplyr::recode(data, !!!lookup)

Also useful with mutate in a dataframe tibble:

df <- tibble(code = data)

df %>% 
  mutate(fruit = recode(code, !!!lookup))
Martin
  • 1,141
  • 14
  • 24