Search code examples
rdata.tablerecode

Recode Numeric To Character


have = data.frame("v1" = c(1,2,3))
want = data.frame("v1" = c("pass", "arb", "rtk"))

I want to recode the numeric to these strings. My attempts at data.table fails:

library(data.table)
have[, c("v1") := recode(v1, 1 == "pass", 2=="arb", 3=="rtk")]

Solution

  • The 'v1' can be used as an index as it is a sequence of values from 1. So, if we pass the new vector to rename in the order we want, then 'pass' will replace whereever there is 1 value in 'v1', 'arb' for 2 and 'rtk' for 3

    library(data.table)
    setDT(have)[, v1 := c('pass', 'arb', 'rtk')[v1]]
    

    Another option is using a named vector to do the match

    nm1 <- setNames(c('pass', 'arb', 'rtk'),  1:3)
    setDT(have)[, v1 := nm1[as.character(v1)]]
    

    Or do this with a factor label option

    setDT(have)[, v1 := as.character(factor(v1, levels = 1:3, 
               labels = c('pass', 'arb', 'rtk')))]
    

    In the OP's code, the recode is using comparison operator (==), instead it would be =. Also, for values that are numeric, wrap with backquote

    setDT(have)[, v1  := dplyr::recode(v1, `1` = "pass", `2`="arb", `3`="rtk")]