3

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.

jpsmith
  • 11,023
  • 5
  • 15
  • 36
JL435
  • 35
  • 4

3 Answers3

1

Another dplyr:

recode(codes, !!!deframe(key))

[1] "ponderosa"   "lodgepole"   "ponderosa"   "Douglas fir" "ponderosa"  
[6] "limber"      "ponderosa"   "lodgepole"  
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

Since you're mentioning dplyr here's a way using summarize

library(dplyr)

tibble(codes) %>% 
  rowwise() %>% 
  summarize(name = key$name[which(codes == key$code)])
# A tibble: 8 × 1
  name       
  <chr>      
1 ponderosa  
2 lodgepole  
3 ponderosa  
4 Douglas fir
5 ponderosa  
6 limber     
7 ponderosa  
8 lodgepole
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29
0

With base R

unname(with(key, setNames(name, code))[as.character(codes)])

-output

[1] "ponderosa"   "lodgepole"   "ponderosa"   "Douglas fir" 
[5] "ponderosa"   "limber"      "ponderosa"   "lodgepole" 

Or with tidyverse

library(dplyr)
library(tibble)
key %>%
   reframe(name = deframe(pick(everything()))[as.character(codes)])

-output

    name
1   ponderosa
2   lodgepole
3   ponderosa
4 Douglas fir
5   ponderosa
6      limber
7   ponderosa
8   lodgepole

Or use

deframe(key)[paste(codes)]
akrun
  • 874,273
  • 37
  • 540
  • 662