2017-02-15 251 views
0

如何用一个向量中的元素替换R中另一个元素的向量元素?如何用一个向量中的元素替换R中另一个元素的向量元素?

我:

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) 

我想DF2看起来像:

a b 
1 x 
2 xx 
3 vf 
4 c 
5 z 
6 z 

到目前为止我试图合并/被加入他们的 “a” 所以我就:

a b b 
1 x NA 
2 w xx 
3 e vf 
4 c NA 
5 t z 
6 z NA 

感谢您的帮助

+0

'df1 $ b = as.character(df1 $ b); df1 $ b [which(match(df1 $ a,df2 $ c)> 0)] = as.character(df2 $ d [which(match(df2 $ c,df1 $ a)> 0)])'' –

回答

1

机智h dplyr

full_join(df1, df2, by = c('a' = 'c')) %>% 
    transmute(a, b = ifelse(is.na(d), b, d)) -> result 
相关问题