Search code examples
rlookup-tables

Change an integer into a specific string in a data.frame


I have a data frame with two columns. The second column contains only integers. More precisely it contains 0,1,2,3 and some NA's. Something like this:

id1    0
id2    1
id3    0
id4    2
id5    3
id6    1
id7    2
id8    NA

What I'm searching for is a command which changes 0 into ZZT the 1 into ZZU and so on. The NA's should stay as NA's. How could this work?

I tried a for loop in combination with some if-statements but this doesn't work. I know such changing thinks are pretty easy in R but it seems that I have a block in my brain.


Solution

  • You can map values using the mapvalues function from the plyr package. Using the example data from Mike Wise's answer:

    library(plyr)
    df$val2 <- mapvalues(df$val,
                               from = c(0,1,2,3,NA),
                               to = c("ZZT", "ZZU", "ZZV", "ZZW", NA))
    

    If you already have the dplyr package loaded (the successor to plyr), call this function usingplyr::mapvalues() as loading plyr on top of dplyr is problematic.