Hi I have two data frames as followed:
df1:
ID x y z
1 a b c
2 a b c
3 a b c
4 a b c
and df2:
ID x y
2 d NA
3 NA e
and I am after a result like this:
df1:
ID x y z
1 a b c
2 d b c
3 a e c
4 a b c
I have been trying to use the match function as suggested by some other posts but I keep getting the issue where my df1 dataframe being replaced with NA values from df2. This is the code I have been using without luck
for (i in names(df2)[2:length(names(df2))]) {
df1[i] <- df2[match(df1$ID, df2$ID)]
}
Thanks
df2 %>% full_join(df1, by = 'ID', suffix = c('', '.1')) %>% mutate(x = coalesce(x, x.1), y = coalesce(y, y.1)) %>% select(-x.1, -y.1) %>% arrange(ID)
. You could do the same in base R, if you like:df3 <- merge(df2, df1, by = 'ID', all = TRUE, suffixes = c('', '.1')); df3$x[is.na(df3$x)] <- df3$x.1[is.na(df3$x)]; df3$y[is.na(df3$y)] <- df3$y.1[is.na(df3$y)]; df3[c('x.1', 'y.1')] <- NULL; df3
– alistaire