问题
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.frame
s. 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