2014-12-03 107 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