如果没有确切的事件日期,我如何为下一个日期创建 dummy/binary 变量?

How can I create a dummy/binary variable to the next date if there is not exactly the event date?

我有以下问题:

我有一个结构如下的面板数据集:

> Symbol    Date    Close.Company   Close.Index   Event
> AAPL  25/05/2021  126900002       13657,1699    14/03/2020
> AAPL  26/05/2021  126849998       13738         14/03/2020
> AAPL  27/05/2021  125279999       13736,2803    14/03/2020
> AAPL  28/05/2021  124610001       13748,7402    14/03/2020
> VISA  02/01/2019  132,919998      6665,93994    12/03/2020
> VISA  03/01/2019  128,130005      6463,5        12/03/2020
> VISA  04/01/2019  133,649994      6738,85986    12/03/2020
> VISA  07/01/2019  136,059998      6823,47022    12/03/2020

现在我试图在事件发生在相应公司的地方创建一个虚拟变量。为此,我尝试了以下代码来查找事件的日期或下一个日期(如果事件不在数据集中):

Kurse_gesamt$EventBin <- ifelse(Kurse_gesamt$Event == Kurse_gesamt$Date | Kurse_gesamt$Date == (Kurse_gesamt$Event+1), 1, 0)

我也试过这段代码,但它 returns 一样:

Kurse_gesamt$EventBin2 <- ifelse(Kurse_gesamt$Event == Kurse_gesamt$Date, 1, (ifelse(Kurse_gesamt$Date == (Kurse_gesamt$Event+1), 1, 0)))

现在发现了两次VISA的事件,因为既有事件又有后续日期。不幸的是,对于 APPL,它找不到任何日期。活动在星期六举行,下一个日期是星期日:

> Symbol    Date    Close.Company   Close.Index Event      EventBin   EventBin2
> VISA  12/03/2020  160,080002      7201,79981  12/03/2020  1            1
> VISA  13/03/2020  175,830002      7874,87988  12/03/2020  1            1
> AAPL  02/01/2019  39480000        6665,93994  14/03/2020  0            0
> AAPL  03/01/2019  35547501        6463,5      14/03/2020  0            0
> AAPL  04/01/2019  37064999        6738,85986  14/03/2020  0            0

现在有没有办法告诉 R 如果事件不在数据集中,它正在寻找下一个可能的日期?

为此,R 应该为事件的每个公司准确输出 1 个虚拟变量。在我的数据集中,也恰好只能在下个月找到下一个可能的日期。

非常感谢!

使用data.table:

library(data.table)

Kurse_Gesamt <- as.data.table(Kurse_Gesamt)
Kurse_Gesamt[difftime(Date, Event) >= 0, Eventbin := ifelse(difftime(Date, Event) == min(difftime(Date, Event)), 1, NA), by=.(Symbol)]