tidyverts / tsibble

Tidy Temporal Data Frames and Tools
https://tsibble.tidyverts.org
GNU General Public License v3.0
528 stars 50 forks source link

intersect methods for year* classes #235

Closed wkdavis closed 3 years ago

wkdavis commented 3 years ago

Would you be open to generics::intersect() methods for yearmonth, yearquarter, and yearweek objects? As an example for intersect.yearmonth()

library(tsibble)
library(generics)
x <- yearmonth(Sys.Date()) + 0:12
y <- yearmonth(Sys.Date()) + 6:18

intersect.yearmonth <- function(x, y, ...) {
  if (!inherits(y, "yearmonth")) {
    stop("'y' must be of class 'yearmonth'")
  }
  tsibble::yearmonth(as.Date(intersect(as.Date(x),
                                       as.Date(y)),
                             origin = as.Date("1970-01-01")))
}

print(x)
#> <yearmonth[13]>
#>  [1] "2020 Nov" "2020 Dec" "2021 Jan" "2021 Feb" "2021 Mar" "2021 Apr"
#>  [7] "2021 May" "2021 Jun" "2021 Jul" "2021 Aug" "2021 Sep" "2021 Oct"
#> [13] "2021 Nov"

print(y)
#> <yearmonth[13]>
#>  [1] "2021 May" "2021 Jun" "2021 Jul" "2021 Aug" "2021 Sep" "2021 Oct"
#>  [7] "2021 Nov" "2021 Dec" "2022 Jan" "2022 Feb" "2022 Mar" "2022 Apr"
#> [13] "2022 May"

intersect(x, y)
#> <yearmonth[7]>
#> [1] "2021 May" "2021 Jun" "2021 Jul" "2021 Aug" "2021 Sep" "2021 Oct" "2021 Nov"

Created on 2020-11-18 by the reprex package (v0.3.0)

I would be happy to create them and open a PR.

earowang commented 3 years ago

Yes, set operations will be useful for these index classes. PRs would be great, but I'd prefer an implementation without coercing Date and year* back and forth.

wkdavis commented 3 years ago

@earowang I think I have found a good way to do it without coercing to/from date. See #244 .

earowang commented 3 years ago

Thanks. Just want to make sure if the setdiff() results gave incorrect results, which I've fixed now.