Check if a date is within an interval in R

前端 未结 6 929
暗喜
暗喜 2020-11-30 12:48

I have these three intervals defined:

YEAR_1  <- interval(ymd(\'2002-09-01\'), ymd(\'2003-08-31\'))
YEAR_2  <- interval(ymd(\'2003-09-01\'), ymd(\'20         


        
6条回答
  •  甜味超标
    2020-11-30 13:34

    With lubridate and mapply:

    library(lubridate)
    
    dates <- # your data here
    
    # no idea how you generated these, so let's just copy them
    YEAR_1 <- interval(ymd('2002-09-01'), ymd('2003-08-31'))
    YEAR_2 <- interval(ymd('2003-09-01'), ymd('2004-08-31')) 
    YEAR_3 <- interval(ymd('2004-09-01'), ymd('2005-08-31'))
    
    # this should scale nicely
    sapply(c(YEAR_1, YEAR_2, YEAR_3), function(x) { mapply(`%within%`, dates, x) })
    

    The result is a matrix with one column per interval:

            [,1]  [,2]  [,3]
      [1,]  TRUE FALSE FALSE
      [2,] FALSE  TRUE FALSE
      [3,] FALSE  TRUE FALSE
      [4,] FALSE  TRUE FALSE
      ... etc. (100 rows in your example data)
    

    There might be a nicer way to code that with purrr, but I am too novice to purrr to see it.

提交回复
热议问题