将两个向量与共同元素对齐 [英] Align two vector with common elements
本文介绍了将两个向量与共同元素对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个向量,其中一些元素是相同的:
I have two vectors where some elements are common:
v1= c('a', 'b', 'c')
v2 = c('b', 'c', 'd')
我想将向量组合成两个 data.frame
.首先,我希望同时使用两个向量中的所有元素,并且两个向量中不匹配的位置都应替换为 NA
:
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
最好的方法是什么?
推荐答案
获取第一个
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
获取第二个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
这篇关于将两个向量与共同元素对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文