4

Take two intervals: [1,6) and [6,12). Number 6 belongs in the second but not the first. Can the same be accomplished in lubridate? (This deals with the issue in 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

Can function %within% be tweaked to exclude upper bounds of intervals?

Any help will be much appreciated.

Community
  • 1
  • 1
emagar
  • 985
  • 2
  • 14
  • 28

2 Answers2

4

Sure thing. I searched lubridate on github to find where %within% is defined. A couple tweaks to the code (changing <= to <):

"%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
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
3

You can define the intA interval ending 1 second before date6:

   intA <- new_interval(date1, date6-1)
   date6 %within% intA 
   #[1] FALSE
nicola
  • 24,005
  • 3
  • 35
  • 56