Home > OS >  Recode a column of numercial values to a new column of text values in R
Recode a column of numercial values to a new column of text values in R

Time:10-29

In R, in a data frame, I want to take the code number of a tree species in one column and create a new column in the data frame with recoded text name of the species like below. I can create a matrix of tree name = code number, but how do I apply this to a long and mixed column of just numerical values?

> treeco <- c(4, 3, 4, 5, 3, 2, 2, 1, 4)
> spcode <- c("oak" = 1, "ash" = 2, "elm" = 3, "beech" = 4, "hazel" = 5)
> treesp <- data.frame(spcode)
> treesp
      species
oak         1
ash         2
elm         3
beech       4
hazel       5

This is the solution I am looking for:

  treeco spcode
1      4  beech
2      3    elm
3      4  beech
4      5  hazel
5      3    elm
6      2    ash
7      2    ash
8      1    oak
9      4  beech

CodePudding user response:

base R

data.frame(treeco, answer = names(spcode)[treeco])
#   treeco answer
# 1      4  beech
# 2      3    elm
# 3      4  beech
# 4      5  hazel
# 5      3    elm
# 6      2    ash
# 7      2    ash
# 8      1    oak
# 9      4  beech

dplyr

It can be slightly confusing when a column-name matches one in the environment, so for the sake of demonstration I'll rename treeco in the tibble so that it is clear which is being used.

library(dplyr)
tibble(tc = treeco) %>%
  mutate(answer = names(spcode)[tc])
# # A tibble: 9 x 2
#      tc answer
#   <dbl> <chr> 
# 1     4 beech 
# 2     3 elm   
# 3     4 beech 
# 4     5 hazel 
# 5     3 elm   
# 6     2 ash   
# 7     2 ash   
# 8     1 oak   
# 9     4 beech 

There's another method that allows you to bring in much more than one extra column: the join/merge.

treecodes <- data.frame(code = spcode, tree = names(spcode))
set.seed(42)
treecodes$rand <- sample(100, size = nrow(treecodes), replace = TRUE)
treecodes
#       code  tree rand
# oak      1   oak   49
# ash      2   ash   65
# elm      3   elm   25
# beech    4 beech   74
# hazel    5 hazel  100
trees <- data.frame(code = treeco)
trees
#   code
# 1    4
# 2    3
# 3    4
# 4    5
# 5    3
# 6    2
# 7    2
# 8    1
# 9    4
trees %>%
  left_join(treecodes, by = "code")
#   code  tree rand
# 1    4 beech   74
# 2    3   elm   25
# 3    4 beech   74
# 4    5 hazel  100
# 5    3   elm   25
# 6    2   ash   65
# 7    2   ash   65
# 8    1   oak   49
# 9    4 beech   74

For more information on joins/merges, see How to join (merge) data frames (inner, outer, left, right) and What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?.

  • Related