Reputation: 175
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
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