简体   繁体   中英

How to check date interval is in another interval

I have created cols and rows with following code

    library(lubridate)    

date1<-ymd_hms("2000-01-01 05:30:00",tz = "US/Eastern")  
date2<- ymd_hms("2000-01-01 00:00:00",tz = "US/Eastern")

cols <- lapply(0:14, function(x){
  mapply(function(y,z){
    interval((date1+days(x)+minutes(y)), (date1+days(x)+minutes(y+z)))
  }, y = c(0,150,420,600,720,840,1080), z = c(600,570,600,600,600,600,600), SIMPLIFY = FALSE)
})

rows <- lapply(0:14, function(x){
  mapply(function(y,z){
    interval((date2+days(x)+minutes(y)), (date2+days(x)+minutes(y+z)))
  }, y = seq(0,1380,60), rep(c(60),24), SIMPLIFY = FALSE)
})  

The requirement is to create a matrix with cols and rows and with 1's and 0's. 1's if row interval is in column interval else with 0's

Intervals are composed of start : date of start, .Data : seconds of duration of the interval and tzone : time zone.

Asumming that you tzone is stable, you only need to reconstruct the start date of the two intervals you want to compare and check that one starts after the second and ends before the second.

Example:

    isIncluded <- function(a,b){
      (a[[1]]@start>=b[[1]]@start & (a[[1]]@start+seconds(a[[1]]@.Data))<=(b[[1]]@start+seconds(b[[1]]@.Data)))
    }

 library(lubridate)    

date1<-ymd_hms("2000-01-01 05:30:00",tz = "US/Eastern")  
date2<- ymd_hms("2000-01-01 00:00:00",tz = "US/Eastern")

cols <- lapply(0:14, function(x){
  mapply(function(y,z){
    interval((date1+days(x)+minutes(y)), (date1+days(x)+minutes(y+z)))
  }, y = c(0,150,420,600,720,840,1080), z = c(600,570,600,600,600,600,600), SIMPLIFY = FALSE)
})

rows <- lapply(0:14, function(x){
  mapply(function(y,z){
    interval((date2+days(x)+minutes(y)), (date2+days(x)+minutes(y+z)))
  }, y = seq(0,1380,60), rep(c(60),24), SIMPLIFY = FALSE)
})  
    x <- cols[[1]][1]
    y <- cols[[1]][2]
    isIncluded(x,y) ## Is included x in y? False
    isIncluded(x,x) ## Is included x in x? True

The rest is just populating the matrix!
Best!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM