简体   繁体   English

根据列中的条件为组分配值(从配置表中提取)

[英]Assign value (stemming from configuration table) to group based on condition in column

I have a data.table DT1 , containing a value per region. 我有一个data.table DT1 ,每个区域包含一个值。 In a configuration table DT2 , I have a mapping of each value per region to a variable number_carrots . 在配置表DT2 ,我将每个区域的每个值映射到变量number_carrots

Is there an elegant data.table way of adding a column ( number_carrots ) to DT1 stemming from the mapping in DT2 ? 是否有一种优雅的data.table方法,可以根据DT2的映射向DT1中添加一列( number_carrots )? I only managed to do this with a loop ... 我只能通过循环来做到这一点...

To give an example. 举个例子。 DT1 is: DT1是:

library(data.table)
region1 = c('Europe', 'Europe', 'Africa', 'Africa', 'Europe', 'Africa')
value1  = c(1, 2, 1, 2, 3, 1)
DT1     = data.table(region1, value1)

> DT1
    region1 value1
1:  Europe      1
2:  Europe      2
3:  Africa      1
4:  Africa      2
5:  Europe      3
6:  Africa      1

And DT2 is: DT2是:

region2         = rep(c('Europe', 'Africa'), each = 3)
value2          = c(1:3, 1:3)
number_carrots  = c(10, 20, 30, 5, 15, 30)

DT2             = data.table(region2, value2, number_carrots)

> DT2
   region2 value2 number_carrots
1:  Europe      1             10
2:  Europe      2             20
3:  Europe      3             30
4:  Africa      1              5
5:  Africa      2             15
6:  Africa      3             30

Using, the mapping from DT2 , I would like to add a column number_carrots to DT1 : 使用从DT2映射,我想向DT1添加一列number_carrots

> DT1
   region1 value1 number_carrots
1:  Europe      1             10
2:  Europe      2             20
3:  Africa      1              5
4:  Africa      2             15
5:  Europe      3             30
6:  Africa      1              5

The OP has requested to add a column number_carrots to DT1 . OP已请求DT1添加一列number_carrots

This can be solved with an update join which modifies DT1 by reference 这可以通过更新 DT1通过引用修改DT1来解决

DT1[DT2, on = .(region1 = region2, value1 = value2), number_carrots := i.number_carrots]
DT1
  region1 value1 number_carrots 1: Europe 1 10 2: Europe 2 20 3: Africa 1 5 4: Africa 2 15 5: Europe 3 30 6: Africa 1 5 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM