【问题标题】:Exclusive time intervals in R's lubridateR 的 lubridate 中的独占时间间隔
【发布时间】:2014-12-03 19:46:18
【问题描述】:

取两个区间:[1,6) 和 [6,12)。 6 号属于第二个,但不属于第一个。是否可以在 lubridate 中完成相同的操作? (This 处理 Python 中的问题...)

library(lubridate)
date1 <- ymd(20010101); date3 <- ymd(20010103); date6 <- ymd(20010106); date12 <- ymd(20010112)
intA <- new_interval(date1, date6); intB <- new_interval(date6, date12)
date3 %within% intA
> TRUE
date3 %within% intB
> FALSE
date6 %within% intB ## I want this to be true
> TRUE
date6 %within% intA ## but this be false...
> TRUE

可以调整函数 %within% 以排除区间的上限吗?

任何帮助将不胜感激。

【问题讨论】:

    标签: r posixct lubridate


    【解决方案1】:

    当然。我搜索了lubridate on github 以找到%within% 的定义位置。对代码进行了一些调整(将 &lt;= 更改为 &lt;):

    "%my_within%" <- function(a,b) standardGeneric("%my_within%")
    setGeneric("%my_within%")
    
    setMethod("%my_within%", signature(b = "Interval"), function(a,b){
        if(!is.instant(a)) stop("Argument 1 is not a recognized date-time")
        a <- as.POSIXct(a)
        (as.numeric(a) - as.numeric(b@start) < b@.Data) & (as.numeric(a) - as.numeric(b@start) >= 0)
    })
    
    setMethod("%my_within%", signature(a = "Interval", b = "Interval"), function(a,b){
        a <- int_standardize(a)
        b <- int_standardize(b)
        start.in <- as.numeric(a@start) >= as.numeric(b@start) 
        end.in <- (as.numeric(a@start) + a@.Data) < (as.numeric(b@start) + b@.Data)
        start.in & end.in
    })
    
    date3 %my_within% intA
    > TRUE
    date3 %my_within% intB
    > FALSE
    date6 %my_within% intB ## I want this to be true
    > TRUE
    date6 %my_within% intA ## False, as desired!
    > FALSE
    

    【讨论】:

      【解决方案2】:

      您可以定义在date6 之前 1 秒结束的 intA 间隔:

         intA <- new_interval(date1, date6-1)
         date6 %within% intA 
         #[1] FALSE
      

      【讨论】:

        猜你喜欢
        • 2022-10-05
        • 2021-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-19
        • 2020-02-24
        相关资源
        最近更新 更多