2014-04-16 32 views
2

这是我第一个问题到StackOverflow。如果我的问题没有被打磨或清楚,我会提前道歉。在R中合并:寻找类似SAS合并输出选项的选项

在SAS中合并时,可以将没有匹配的行输出到替代数据集。

例如,

data matched nomatch_a nomatch_b; 
    merge A(in=a) B(in=b); 
    by var; 
    if a and b then output matched; 
    else if a and not b then output nomatch_a; 
    else if b and not a then output nomatch_b; 

在这种情况下:
- 这是成功合并输出到匹配
行 - 在DataSet中的行未在b匹配输出到nomatch_a
- 并且数据集B中没有A中匹配的行输出到nomatch_b。

我期待在R中做类似的事情。它不一定是单线,但我想要一个优雅的解决方案。我知道有all.x,all.y选项,但我不能完全调整这些选项来获得我想要的。我会感激你的想法!

+0

你想合并什么?数据帧,矢量,矩阵等?将有助于创建一个输入和输出数据应该看起来像什么的小例子,可直接读入R. – Joe

回答

1
#if a and b then output matched; 

matched <- merge(a,b, by= "var") 

默认情况下'all'参数为FALSE,这会给你“内部连接”。

# else if a and not b then output nomatch_a; 

nomatch_a <- a[ !a$var %in% unique(b$var) , ] 

# else if b and not a then output nomatch_b; 

nomatch_b <- b[ !b$var %in% unique(a$var) , ] 

第二个两个赋值构造逻辑向量并使用“[”函数为TRUE行提取整行。我不认为有任何单线队员,但是你几乎不可能称之为SAS单线程可以吗?我想你可以先使用all=TRUE,然后从“完全外部连接”值中进行类似的提取,但对于我来说,对于我来说,似乎更简单。