Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recoding values with dpylr using a lookup table

Tags:

r

dplyr

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.

like image 762
Bushroot Avatar asked Jan 08 '17 14:01

Bushroot


3 Answers

do.call(dplyr::recode, c(list(data), lookup))
[1] "Pear" "c"    "d"    "c"    "Pear" "Pear" "d"    "c"    "d"    "c"
like image 183
Axeman Avatar answered Nov 01 '22 22:11

Axeman


We can use base R

v1 <- unlist(lookup)[data]
ifelse(is.na(v1), data, v1)
like image 31
akrun Avatar answered Nov 01 '22 23:11

akrun


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))
like image 4
Martin Avatar answered Nov 01 '22 22:11

Martin