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.
do.call(dplyr::recode, c(list(data), lookup))
[1] "Pear" "c" "d" "c" "Pear" "Pear" "d" "c" "d" "c"
We can use base R
v1 <- unlist(lookup)[data]
ifelse(is.na(v1), data, v1)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With