在 R 中按日期范围创建虚拟变量

Creating Dummy Variables by Date Range in R

我想创建虚拟变量,根据日期范围指示哪个产品版本有效,即在发布日期和下一个版本发布日期之间,而不是手动执行。我有几百个版本及其相应的发布日期和下一个版本的发布时间,我将 merge/join 此数据与 Purchases 数据框。

目前我有两个数据框(版本和购买)如下所示:

View(Version)   
Type Version    Release_Date    Next_Release
A       1.2.3   2013-11-14     2014-01-11
B       1.3.1   2014-01-11     2014-02-20
A       1.5.1   2014-02-20     2014-03-08
A       1.5.2   2014-03-08     2014-04-06
B       1.5.3   2014-04-06     2014-04-12
A       1.5.4   2014-04-12     2014-04-15
B       1.5.5   2014-05-15     2014-05-20
B       1.6.1   2014-05-20     2014-06-26
A       1.6.2   2014-06-26     2014-07-14

View(Purchases)
TIMESTAMP   Amount 
2013-11-14   15.44
2013-11-14   13.39
2013-11-14   15.35
2013-11-15   86.43
2014-01-15   12.30
2014-01-17   23.55

我想根据版本生效的日期范围为数据框中的每个版本创建虚拟变量 'Purchases'。即,如果购买的时间戳在该版本生效的日期范围内,则该版本虚拟 = 1,否则为 0。

View(Purchases)
TIMESTAMP   Amount Version_1.2.3  Version_1.3.1  ....
2013-11-14   15.44      1              0
2013-11-14   13.39      1              0
2013-11-14   15.35      1              0
2013-11-15   86.43      1              0
2014-01-15   12.30      0              1
2014-01-17   23.55      0              1 
....

提前感谢您的任何建议或帮助。

任务可以分为两个子任务:

  1. 在购买的TIMESTAMP之前找到最近的Release_Date
  2. 从长格式重塑为宽格式。

为了找到最新版本,data.table 包提供了两种可能性,

一个滚动连接

library(data.table)
setDT(Version)
setDT(Purchases)

Version[Purchases, on = .(Release_Date = TIMESTAMP), roll = TRUE,
        .(TIMESTAMP = i.TIMESTAMP, Amount, Version)]
    TIMESTAMP Amount Version
1: 2013-11-14  15.44   1.2.3
2: 2013-11-14  13.39   1.2.3
3: 2013-11-14  15.35   1.2.3
4: 2013-11-15  86.43   1.2.3
5: 2014-01-15  12.30   1.3.1
6: 2014-01-17  23.55   1.3.1

非等值连接

Version[Purchases, on = .(Release_Date <= TIMESTAMP), mult = "last",
        .(TIMESTAMP = i.TIMESTAMP, Amount, Version)]

产生相同的结果。

为了重塑,dcast()函数与length()一起用于聚合:

# rolling join
Version[Purchases, on = .(Release_Date = TIMESTAMP), roll = TRUE,
        .(TIMESTAMP = i.TIMESTAMP, Amount, Version)][
  , dcast(.SD, TIMESTAMP + Amount ~ Version, length)]
    TIMESTAMP Amount 1.2.3 1.3.1
1: 2013-11-14  13.39     1     0
2: 2013-11-14  15.35     1     0
3: 2013-11-14  15.44     1     0
4: 2013-11-15  86.43     1     0
5: 2014-01-15  12.30     0     1
6: 2014-01-17  23.55     0     1

或者,如果列在重塑期间需要重命名

# non-equi join
Version[Purchases, on = .(Release_Date <= TIMESTAMP), mult = "last",
        .(TIMESTAMP = i.TIMESTAMP, Amount, Version)][
  , dcast(.SD, TIMESTAMP + Amount ~ paste0("Version_", Version), length)]
    TIMESTAMP Amount Version_1.2.3 Version_1.3.1
1: 2013-11-14  13.39             1             0
2: 2013-11-14  15.35             1             0
3: 2013-11-14  15.44             1             0
4: 2013-11-15  86.43             1             0
5: 2014-01-15  12.30             0             1
6: 2014-01-17  23.55             0             1