Skip to content

Commit 971de95

Browse files
committed
made min/max/range safer
1 parent 04d528a commit 971de95

2 files changed

Lines changed: 47 additions & 2 deletions

File tree

R/arithmetic.R

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
# Group generics ----------------------------------------------------------
22

3+
#' Maxima and Minima for date_xx
4+
#'
5+
#' @param ... date_xx vectors. It is up to the user to ensure that they are
6+
#' of the same subclass.
7+
#' @param na.rm
8+
#'
9+
#' @return
10+
#' @export
11+
#'
12+
#' @examples
313
Summary.date_xx <- function (
414
...,
515
na.rm
@@ -8,14 +18,44 @@ Summary.date_xx <- function (
818
.Generic %in% c("min", "max", "range"),
919
.Generic, "not defined for 'date_xx' Objects"
1020
)
21+
dots <- list(...)
22+
class <- vapply(dots, which_date_xx, character(1))
23+
assert(
24+
all_are_identical(class),
25+
"All inputs must have the same <date_xx> subclass"
26+
)
27+
1128
res <- NextMethod(.Generic)
12-
class(res) <- class(..1)
13-
res
29+
30+
switch(
31+
class[[1]],
32+
date_yq = as_date_yq(res),
33+
date_ym = as_date_ym(res),
34+
date_yw = as_date_yw(res),
35+
date_y = as_date_y(res)
36+
)
1437
}
1538

1639

1740

1841

42+
#' Comparison Operators for date_xx
43+
#'
44+
#' @param e1,e2 Objects with the same `date_xx` subclass (one of them can also
45+
#' be integer)
46+
#'
47+
#' @return a `logical` scalar
48+
#' @export
49+
#'
50+
#' @examples
51+
#' date_yq(2015, 1) < date_yq(2015, 2)
52+
#'
53+
#' # comparison with integers is ok
54+
#' date_yq(2015, 1) < 20152
55+
#'
56+
#' # but two different date_xx cannot be compared#'
57+
#' try(date_yq(2015, 1) < date_ym(2015, 2))
58+
#'
1959
Ops.date_xx <- function (
2060
e1,
2161
e2

tests/testthat/test_arithmetic.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ test_that("range.date_xx and min/max work", {
1414

1515
expect_identical(min(q), date_yq(2014, 1))
1616
expect_identical(max(q), date_yq(2014, 4))
17+
18+
expect_error(
19+
max(date_yq(2014, 1), date_ym(2014, 5)),
20+
"subclass"
21+
)
1722
})
1823

1924

0 commit comments

Comments
 (0)