这是使用data.table()
而不是data.frame()
复制上一篇文章(How to join (merge) data frames (inner, outer, left, right)?)。
假设我有两个数据表:
library(data.table)
dt1 = data.table(CustomerID=c(1:6),Product=c(rep("Toaster",3),rep("Radio",3)))
dt2 = data.table(CustomerID=c(2,4,6),State=c(rep("Alabama",2),rep("Ohio",1)))
dt1
CustomerID Product
1: 1 Toaster
2: 2 Toaster
3: 3 Toaster
4: 4 Radio
5: 5 Radio
6: 6 Radio
dt2
CustomerID State
1: 2 Alabama
2: 4 Alabama
3: 6 Ohio
setkey(dt1,CustomerID)
setkey(dt2, CustomerID)
merge()
上使用data.table
的默认设置是右连接。其他人的语法是什么?
#Outer join:
#Right outer (data.table default):
dtro <- merge(dt1,dt2); dtro
CustomerID Product State
1: 2 Toaster Alabama
2: 4 Radio Alabama
3: 6 Radio Ohio
#Left outer:
#Cross join: