1

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?

Henrik
  • 65,555
  • 14
  • 143
  • 159
zesla
  • 11,155
  • 16
  • 82
  • 147

2 Answers2

4

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
BENY
  • 317,841
  • 20
  • 164
  • 234
0

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
MKR
  • 19,739
  • 4
  • 23
  • 33