在 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 进行数据表连接

Passons à la pratique !

在 R 中使用 data.table 进行数据表连接

Preparing Video For Download...