R 的 data.table 資料合併
Scott Ritchie
Postdoctoral Researcher in Systems Genomics
一般 data.table 語法形式
DT[i, j, by]
| | |
| | --> 依哪些欄位分組?
| -----> 要做什麼?
--------> 作用在哪些列?
一般 data.table 連接語法形式
DT[i, on]
| |
| ----> 連接鍵欄位
--------> 要連接到哪個 data.table?
預設連接為右連接(right join)
demographics[shipping, on = .(name)]

list() 或 .() 中的變數,會在兩個 data.table 的欄名中查找
shipping[demographics, on = list(name)]
shipping[demographics, on = .(name)]
也可使用字元向量
join_key <- c("name")
shipping[demographics, on = join_key]
記住:左連接等同於交換順序的右連接:
shipping[demographics, on = .(name)]

將 nomatch = 0 設為內連接(inner join):
shipping[demographics, on = .(name), nomatch = 0]

data.table 語法不支援,請改用 merge():
merge(demographics, shipping, by = "name", all = TRUE)

篩選在另一個 data.table 中沒有對應的列
demographics[!shipping, on = .(name)]

R 的 data.table 資料合併