R 的 data.table 資料合併
Scott Ritchie
Postdoctoral Researcher in Systems Genomics
data.table 可串接多段運算:
demographics[...][...]
連接串接的一般形式:
DT1[DT2, on][i, j, by]
| | | | |
| | | | --> 依哪些欄位分組?
| | | -----> 要做什麼?
| | --------> 哪些列?
| ------------> 連接鍵欄位
-----------------> 要連到哪個 data.table?
customers <- data.table(name = c("Mark", "Matt", "Angela", "Michelle"),
gender = c("M", "M", "F", "F"),
age = c(54, 43, 39, 63))
customers
name gender age
1: Mark M 54
2: Matt M 43
3: Angela F 39
4: Michelle F 63
purchases <- data.table(name = c("Mark", "Matt", "Angela", "Michelle"),
sales = c(1, 5, 4, 3),
spent = c(41.70, 41.78, 50.77, 60.01))
purchases
name sales spent
1: Mark 1 41.70
2: Matt 5 41.78
3: Angela 4 50.77
4: Michelle 3 60.01
customers[purchases,
on = .(name)][sales > 1,
j = .(avg_spent = sum(spent) / sum(sales)),
by = .(gender)]
gender avg_spent
1: M 13.91333
2: F 20.00333
含連接的運算:
DT1[DT2, on, j]
| | |
| | ----> 在連接結果上要做什麼?
| --------> 使用哪些欄位當鍵?
-------------> 要連到哪個 data.table?
對大型 data.table 很有效率!
新增欄位會在主要的 data.table 中進行:
customers[purchases, on = .(name), return_customer := sales > 1]
customers
name gender age return_customer
1: Mark M 54 FALSE
2: Matt M 43 TRUE
3: Angela F 39 TRUE
4: Michelle F 63 TRUE
by = .EACHI 會依 DT2 的每一列來分組 j
DT1[DT2, on, j, by = .EACHI]
| | | |
| | | --> 依 DT1 中的每個相符項分組。
| | -----> 在連接結果上要做什麼?
| ---------> 使用哪些欄位當鍵?
--------------> 要連到哪個 data.table?
shipping[customers, on = .(name),
j = .("# of shipping addresses" = .N),
by = .EACHI]

在 by 指定欄位分組時,運算會限制在主要 data.table:
DT1[DT2, on, j, by]
| | | |
| | | --> 在 DT1 中依哪些欄位分組?
| | -----> 在 DT1 的欄位上要做什麼?
| ---------> 使用哪些欄位當鍵?
--------------> 要連到哪個 data.table?
在 customers 中連接並依群組計算:
customers[shipping, on = .(name),
.(avg_age = mean(age)), by = .(gender)]
gender avg_age
1: M 46.66667
2: F 39.00000
R 的 data.table 資料合併