Search code examples
rreplacerenamemutate

Replacing unique values in vector with names based on a key


I have vector containing several unique values:

codes <- c(122, 108, 122, 202, 122, 113, 122, 108)

Each of these values corresponds to the name for a specific tree species: 122 - ponderosa, 108 - lodgepole, 113 - limber, 202 - Douglas fir,

I have the above key set up as a data.frame:

key <- data.frame(code = c(108, 113, 122, 202), name = c('lodgepole', 'limber', 
                      'ponderosa', 'Douglas fir'))

I would like to change the values in the 'codes' vector to the corresponding tree species name using the key. How do I do this without using nested ifelse() statements that I have been using?

I've looked into the various mutate functions in dplyr to do this, but can't seem to find a solution.


Solution

  • Another dplyr:

    recode(codes, !!!deframe(key))
    
    [1] "ponderosa"   "lodgepole"   "ponderosa"   "Douglas fir" "ponderosa"  
    [6] "limber"      "ponderosa"   "lodgepole"