Roggan
Roggan

Reputation: 175

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!

Upvotes: 1

Views: 195

Answers (2)

Sai Prabhanjan Reddy
Sai Prabhanjan Reddy

Reputation: 536

Using dplyr() and you can preserve new_ID if required removing select()

library(dplyr)
df %>% left_join(code,by = c("ID" = "orig_ID")) %>% mutate(ID = new_ID) %>% select(-new_ID)

Upvotes: 0

akrun
akrun

Reputation: 887173

We can use match

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

Upvotes: 1

Related Questions