取两个区间:[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% 以排除区间的上限吗?

任何帮助都感激不尽。

最佳答案

肯定的事。我搜索了 lubridate on github 以找到 %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

关于r - R's lubridate 中的独家时间间隔,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27280338/

10-12 19:17