Recoding values ​​with dpylr using lookup table

Is there a way to use the dpylr recoding function along 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 mapvalues and revalue from the plyr package. Combining them is possible, as described here . However, I am wondering if something like this is possible with dplyr.

+5
source share
2 answers
 do.call(dplyr::recode, c(list(data), lookup)) 
 [1] "Pear" "c" "d" "c" "Pear" "Pear" "d" "c" "d" "c" 
+5
source

We can use base R

 v1 <- unlist(lookup)[data] ifelse(is.na(v1), data, v1) 
+4
source

Source: https://habr.com/ru/post/1262492/


All Articles