Search code examples
rfindreplaceall

R - How to replace a set of values with another set of values


I have this problem which I can solve manually but I feel there must be an easier answer. I want to replace 2 with A, 22 with B, 4 with C, ... I have all the values I want to replace in an array and another [A,B,C,D,...]. Is there an easy way to perform this replacement? Thanks, Miguel


Solution

  • Use data.table

    DT[column1 == "2", column1 := "A"]
    

    If you want to do a group of them at a time, then use setkey from data.table and merge the dataset with the reference dataset.

    setkeyv(DT, 'column1')
    setkeyv(referenceSet, 'oldVars')
    
    merge(DT, referenceSet, all.x = TRUE)