Align two vector with common elements [duplicate]

家住魔仙堡 提交于 2020-07-23 04:31:09

问题


I have two vectors where some elements are common:

v1= c('a', 'b', 'c')
v2 = c('b', 'c', 'd')

I want to combine the vectors into two data.frames. In the first I want all elements from both vectors, and non-matching positions in either vector should be replaced by NA:

v1   v2
a    NA
b    b
c    c
NA   d

In the second data frame, I want the elements from from the first vector and the corresponding matches in the second:

v1   v2
a    NA
b    b
c    c

What is the best way to do it?


回答1:


Get the first one

mergedf=merge(data.frame('key'=v1,v1),data.frame('key'=v2,v2),by='key',all=T)
mergedf
  key   v1   v2
1   a    a <NA>
2   b    b    b
3   c    c    c
4   d <NA>    d

Get the 2nd df

mergedf[!is.na(mergedf$v1),]
  key   v1   v2
1   a    a <NA>
2   b    b    b
3   c    c    c
4   d <NA>    d



回答2:


An option can be to go for dplyr based solution. You can use full_join and left_join as:

library(dplyr)

v1= c('a', 'b', 'c')
v2 = c('b', 'c', 'd')

full_join(data.frame(key=v1, v1, stringsAsFactors = FALSE),
          data.frame(key=v2, v2, stringsAsFactors = FALSE), by="key") %>%
  select(-key)

#     v1   v2
# 1    a <NA>
# 2    b    b
# 3    c    c
# 4 <NA>    d


left_join(data.frame(key=v1, v1, stringsAsFactors = FALSE),
          data.frame(key=v2, v2, stringsAsFactors = FALSE), by="key") %>%
  select(-key)

#   v1   v2
# 1  a <NA>
# 2  b    b
# 3  c    c


来源:https://stackoverflow.com/questions/51990786/align-two-vector-with-common-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!