Replacing numbers with text in a dataframe

gsub, r, replace

Solution

Why not just use `labels` from `factor`?

set.seed(1)
x <- sample(c(1, 2, 3, 5, 10, 11, 13), 20, TRUE)
x
#  [1]  2  3 10 13  2 13 13 10 10  1  2  2 10  3 11  5 11 13  3 11
factor(x, levels = c(1, 2, 3, 5, 10, 11, 13), 
       labels = c("w.subboreal", "PICO", "ABLA.PIEN", "dry.forest", 
                  "shrubby", "agriculture", "disturbed"))
#  [1] PICO        ABLA.PIEN   shrubby     disturbed   PICO        disturbed   disturbed  
#  [8] shrubby     shrubby     w.subboreal PICO        PICO        shrubby     ABLA.PIEN  
# [15] agriculture dry.forest  agriculture disturbed   ABLA.PIEN   agriculture
# Levels: w.subboreal PICO ABLA.PIEN dry.forest shrubby agriculture disturbed

Problem

I'm sure there is a simple answer but I've been searching and I couldn't find anything on this. I have a data frame (sdata) with a column named "`landcover`" This is a categorical variable but as of now each landcover type is indicated by a number. I'd like to replace the landcover number codes with text and have figured out how to do this partly with: ``` sdata$landcover<- as.factor(sdata$landcover) levels(sdata$landcover) <- gsub("1", "w.subboreal", levels(sdata$landcover)) levels(sdata$landcover) <- gsub("2", "PICO", levels(sdata$landcover)) levels(sdata$landcover) <- gsub("3", "ABLA.PIEN", levels(sdata$landcover)) levels(sdata$landcover) <- gsub("5", "dry.forest", levels(sdata$landcover)) levels(sdata$landcover) <- gsub("10", "shrubby", levels(sdata$landcover)) levels(sdata$landcover) <- gsub("11", "agriculture", levels(sdata$landcover)) levels(sdata$landcover) <- gsub("13", "disturbed", levels(sdata$landcover)) ``` This works for single digit numbers but, for example, the number 13 turns into "`w.subborealABLA.PIEN`"(i.e. combination of 1 and 3) and the number 10 turns into "`w.subboreal0`" (combination of 1 and 0). How can I make sure that double digit numbers are considered as one number, not two separate single digit numbers to be replaced? Thank you!

Original source