lundi 2 juillet 2018

R - Merge and Replace Column If ID Found on Another Data Frame

I have two data frames as below and am trying to improve my code so the letters column in df1 should replaced with the letters column in df2 if they match.

df1:
ID  Letters
1   A
2   B
3   C
4   D
5   E

df2:
ID  letters2
1   F
3   F
4   F

desired:
ID  letters
1   F
2   B
3   F
4   D
5   F

It would be like doing the following by in one line:

desired <- merge(df1, df2, by = "ID", all.x = T)
desired$letters <- ifelse(is.na(desired$letters2), desired$letters, desired$letters2)
desired$letters2 <- NULL

Aucun commentaire:

Enregistrer un commentaire