Search code examples
rtidyversexts

Does tidyverse offer xts range-based queries?


xts allows natural range-based time quires like this willsh["1979-12-31/2017-12-31"]

Does tidyverse offer something like that?


Solution

  • lubridate has interval class. Any of these can be used to represent the interval from 1979-12-31 to 2017-12-31.

    library(dplyr)
    library(lubridate)
    
    ival1 <- interval("19791231/20171231")
    ival1a <- interval("1979-12-31/2017-12-31") 
    ival2 <- interval("19791231/P38Y")
    ival2a <- interval("1979-12-31/P38Y")
    ival3 <- interval(ymd(19791231), ymd(20171231))
    ival3a <- interval(ymd("1979-12-31"), ymd("2017-12-31"))
    
    sapply(list(ival1, ival1a, ival2, ival2a, ival3, ival3a), identical, ival1)
    ## [1] TRUE TRUE TRUE TRUE TRUE TRUE
    

    %within% can be used to check whether a date falls in an interval.

    ymd(c(19791230, 19791231, 19800101, 20171230, 20171231, 20180101)) %within% ival1
    ## [1] FALSE  TRUE  TRUE  TRUE  TRUE FALSE
    

    We can use it like this:

    # test input
    willsh <- tibble(Date = seq(ymd(19700101), ymd(20210101), by = "10 year"), 
                 year = year(Date))
    
    willsh %>% filter(Date %within% interval("1979-12-31/2017-12-31"))
    ## # A tibble: 4 x 2
    ##   Date        year
    ##   <date>     <dbl>
    ## 1 1980-01-01  1980
    ## 2 1990-01-01  1990
    ## 3 2000-01-01  2000
    ## 4 2010-01-01  2010