2014-04-16 33 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,然後從「完全外部連接」值中進行類似的提取,但對於我來說,對於我來說,似乎更簡單。