簡體   English   中英

查找其日期間隔包含守時日期的值

[英]Finding value whose date interval encompasses punctual date

我有一個理論值的data.table給出了一個間隔:

firstDate   lastDate    theoric
2017-01-01  2017-01-03  10
2017-01-05  2017-01-25  20
2017-02-01  2017-08-31  30

另一方面,我有准時的測量值:

datetime      measured
2017-01-02       11
2017-01-08       22
2017-01-09       19
2017-01-26       25
2017-03-02       32

我想為每個測量值都具有相應的理論值(其間隔包括測量日期的理論值)。

注意:1.理論間隔不能重疊。 2.如果測量不在任何理論間隔內,則返回NA。

預期產量:

datetime    measured  theoric
2017-01-02  11        10
2017-01-08  22        20
2017-01-09  19        20
2017-01-26  25        NA
2017-03-02  32        30

可重現的數據集:

theoricDt <- structure(list(firstDate = structure(c(1483228800, 1483574400, 1485907200), class = c("POSIXct", "POSIXt"), tzone = "GMT"),     lastDate = structure(c(1483401600, 1485302400, 1504137600 ), class = c("POSIXct", "POSIXt"), tzone = "GMT"), theoric = c(10, 20, 30)), .Names = c("firstDate", "lastDate", "theoric"), row.names = c(NA, -3L), class = c("data.table", "data.frame"))
measureDt <- structure(list(datetime = structure(c(1483315200, 1483833600, 1483920000, 1485388800, 1488412800), class = c("POSIXct", "POSIXt"), tzone = "GMT"), measured = c(11, 22, 19, 25, 32)), .Names = c("datetime", "measured"), row.names = c(NA, -5L), class = c("data.table","data.frame"))

您可以使用非等額聯接:

measureDt[theoricDt, on = .(datetime >= firstDate, datetime <= lastDate),
          theoric := i.theoric]

measureDt
#     datetime measured theoric
#1: 2017-01-02       11      10
#2: 2017-01-08       22      20
#3: 2017-01-09       19      20
#4: 2017-01-26       25      NA
#5: 2017-03-02       32      30

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM