2014-12-03 70 views
2

取两个区间:[1,6]和[6,12]。 6号属于第二个,但不是第一个。同样可以在lubridate中完成吗? (This涉及Python中的问题...)R的独特时间间隔

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 

可以起到%以内%进行调整,以排除区间的上限?

任何帮助将不胜感激。

回答

2

当然可以。我搜索了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([email protected]) < [email protected]) & (as.numeric(a) - as.numeric([email protected]) >= 0) 
}) 

setMethod("%my_within%", signature(a = "Interval", b = "Interval"), function(a,b){ 
    a <- int_standardize(a) 
    b <- int_standardize(b) 
    start.in <- as.numeric([email protected]) >= as.numeric([email protected]) 
    end.in <- (as.numeric([email protected]) + [email protected]) < (as.numeric([email protected]) + [email protected]) 
    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 
+0

感谢@Gregor,你是男人! – emagar 2014-12-03 21:38:20

1

可以date6之前定义intA间隔卷末第1次:

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