lubridate icon indicating copy to clipboard operation
lubridate copied to clipboard

Support (sum, min, max, seq, abs, mean, median) for Period and Duration objects

Open earowang opened this issue 4 years ago • 4 comments

Since Period class can be sorted now, shall we expect vec_math() to return the class itself?

p <- lubridate::period(year = 1:5)
p
#> [1] "1y 0m 0d 0H 0M 0S" "2y 0m 0d 0H 0M 0S" "3y 0m 0d 0H 0M 0S"
#> [4] "4y 0m 0d 0H 0M 0S" "5y 0m 0d 0H 0M 0S"
min(p)
#> [1] 0
max(p)
#> [1] 0
range(p)
#> [1] 0 1

Feature request: It would be useful to add the seq() method for Period, in addition to its arithmetics.

p + lubridate::period(year = 1)
#> [1] "2y 0m 0d 0H 0M 0S" "3y 0m 0d 0H 0M 0S" "4y 0m 0d 0H 0M 0S"
#> [4] "5y 0m 0d 0H 0M 0S" "6y 0m 0d 0H 0M 0S"
seq(p[5], by = "1 year", length.out = 1)
#> Error in (0L:(length.out - 1L)) * by: non-numeric argument to binary operator

Created on 2020-06-21 by the reprex package (v0.3.0)

Happy to send PRs, if needed.

earowang avatar Jun 20 '20 23:06 earowang

@DavisVaughan any thoughts?

vspinu avatar Jun 22 '20 07:06 vspinu

As of right now, vec_math() isn't being called for lubridate objects. I don't think this currently has much to do with vctrs? I would imagine it is falling through to the default min() implementation unless lubridate has added one specifically for period objects.

It seems like a useful thing to add though

DavisVaughan avatar Jun 23 '20 20:06 DavisVaughan

Related #918

vspinu avatar Nov 05 '22 12:11 vspinu

To add to the list:

  • for(p in periods) {} loops on the seconds
  • ifelse(TRUE, period1, period2) returns the seconds (dplyr::if_else() works fine).
  • period_1 | period_2 and period_1 || period_2 are FALSE if seconds are zero, despite having non zero component
  • if (period_1) similarly will take period_1 as FALSE if it has zero seconds, even if it has other components

If the type was built on top of NA rather than 0 (and we'd have a separate seconds component) we would probably spot the issue more easily due to NA propagation, now the behavior is very dangerous in my opinion.

FWIW defining this seems to not affect what's working and improve all of the above except control flow (and the NA strategy would fix if()) :

mean.Period <- 
  median.Period <- 
  Math.Period <- 
  Ops.Period <- 
  Summary.Period <- 
  Complex.Period <- 
  function(x, ...) {
  stop("nope")
}

moodymudskipper avatar Jul 17 '23 13:07 moodymudskipper