tidyverse / lubridate

Make working with dates in R just that little bit easier
https://lubridate.tidyverse.org
GNU General Public License v3.0
724 stars 207 forks source link

Implement Set Operations methods for Dates #1155

Closed DanChaltiel closed 1 week ago

DanChaltiel commented 6 months ago

Hi,

Using set operations like setdiff on dates removes the date class.

Here is a reprex with a very naive workaround:

library(lubridate)  
a = seq(as_date(1), as_date(10), by=1) 
b = seq(as_date(5), as_date(10), by=1) 

setdiff(a, b)  
#> [1] 1 2 3 4

setdiff.Date = function(x, y) base::setdiff(x, y) |> as_date()
setdiff(a, b)
#> [1] "1970-01-02" "1970-01-03" "1970-01-04" "1970-01-05"

Created on 2024-02-06 with reprex v2.0.2

Of course, the same problem and solution happen for other set operations like intersect and others.

I guess that since they are implemented for the Interval class, it would make sense to implement them for Date. I'm not using other lubridate classes much but maybe they have the same problem.

DavisVaughan commented 1 week ago

Date comes from base R, not from lubridate, so I don't think it would be appropriate for us to write an S3 method in this case.

You can use vctrs::vec_set_difference() if you need a generic version that works with pretty much all S3 types.

library(lubridate)  
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
a = seq(as_date(1), as_date(10), by=1) 
b = seq(as_date(5), as_date(10), by=1) 

vctrs::vec_set_difference(a, b)  
#> [1] "1970-01-02" "1970-01-03" "1970-01-04" "1970-01-05"

Created on 2024-08-05 with reprex v2.0.2