在 data.table 工作流程中加入連接

R 的 data.table 資料合併

Scott Ritchie

Postdoctoral Researcher in Systems Genomics

串接 data.table 運算

data.table 可串接多段運算:

demographics[...][...]

連接串接的一般形式:

DT1[DT2, on][i, j, by]
    |    |   |  |  |
    |    |   |  |   --> 依哪些欄位分組?
    |    |   |   -----> 要做什麼?
    |    |    --------> 哪些列?
    |     ------------> 連接鍵欄位
     -----------------> 要連到哪個 data.table?
R 的 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
R 的 data.table 資料合併

先連接再運算

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
R 的 data.table 資料合併

先連接再運算

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
R 的 data.table 資料合併

用連接進行運算

含連接的運算:

DT1[DT2, on, j]
    |    |   | 
    |    |    ----> 在連接結果上要做什麼?
    |     --------> 使用哪些欄位當鍵? 
     -------------> 要連到哪個 data.table?

對大型 data.table 很有效率!

R 的 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
R 的 data.table 資料合併

依相符項分組

by = .EACHI 會依 DT2 的每一列來分組 j

DT1[DT2, on, j, by = .EACHI]
    |    |   |  |
    |    |   |   --> 依 DT1 中的每個相符項分組。
    |    |    -----> 在連接結果上要做什麼?
    |     ---------> 使用哪些欄位當鍵? 
     --------------> 要連到哪個 data.table?
R 的 data.table 資料合併

依相符項分組

shipping[customers, on = .(name), 
         j = .("# of shipping addresses" = .N),
         by = .EACHI]

R 的 data.table 資料合併

連接時依欄位分組

by 指定欄位分組時,運算會限制在主要 data.table:

DT1[DT2, on, j, by]
    |    |   |  |
    |    |   |   --> 在 DT1 中依哪些欄位分組?
    |    |    -----> 在 DT1 的欄位上要做什麼?
    |     ---------> 使用哪些欄位當鍵? 
     --------------> 要連到哪個 data.table?
R 的 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 資料合併

一起來練習吧!

R 的 data.table 資料合併

Preparing Video For Download...