Reputation: 17
how to replace elements of a vector with elements from a vector which match throughout another item in R?
I have:
a <- c(1,2,3,4,5,6)
b <- c('x','w','e','c','t','z')
c <- c(2,3,5)
d <- c('xx','vf','z')
df1 <- data.frame(a,b)
df2 <- data.frame(c,d)
I want df2 look like that:
a b
1 x
2 xx
3 vf
4 c
5 z
6 z
I have tried so far to merge/join them by "a" so i got:
a b b
1 x NA
2 w xx
3 e vf
4 c NA
5 t z
6 z NA
Thank you for your help
Upvotes: 0
Views: 49
Reputation: 13680
With dplyr
:
full_join(df1, df2, by = c('a' = 'c')) %>%
transmute(a, b = ifelse(is.na(d), b, d)) -> result
Upvotes: 1