Search code examples
ridentifier

Replace IDs with IDs based on a separate "ID code"


I have data looking like this:

df <- data.frame(ID = c(11243, 11243, 12335, 12335, 13288), x1 = seq(1, 5), x2 
= seq(42, 46))

I would like to change the "original" IDs in df to "new IDs" based according to a conversion "code" I have stored in another DF:

code <- data.frame(orig_ID = c(11243, 12335, 13288), new_ID = c(1, 2, 3))

df should look like this (with the replaced IDs) in the end:

df <- data.frame(ID = c(1, 1, 2, 2, 3), x1 = seq(1, 5), 
x2 = seq(42, 46))

Any help is much appreciated!


Solution

  • We can use match

    df$ID <- code$new_ID[match(df$ID, code$orig_ID)]