[英]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.