R的lubridate包中的独占时间间隔

4

考虑两个区间:[1,6) 和 [6,12)。数字 6 属于第二个区间但不属于第一个区间。在 lubridate 中是否也可以实现相同的功能?(这里讨论了 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%是否可以进行调整以排除区间的上限?

非常感谢您的帮助。

2个回答

4
当然。我搜索了github上的lubridate,找到了%within%的定义位置。对代码进行了一些微调(将<=更改为<):
"%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

3

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接