Skip to content

Commit

Permalink
Implement unique() S3 methods (r-quantities#277)
Browse files Browse the repository at this point in the history
* Implement `unique.units()`
* Implement `unique.mixed_units()`
* Add tests
  • Loading branch information
lewinfox committed Jun 8, 2021
1 parent 019b3f7 commit 00f23ac
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NAMESPACE
Expand Up @@ -61,6 +61,8 @@ S3method(set_units,units)
S3method(str,mixed_units)
S3method(str,units)
S3method(summary,units)
S3method(unique,mixed_units)
S3method(unique,units)
S3method(units,mixed_units)
S3method(units,symbolic_units)
S3method(units,units)
Expand Down
5 changes: 5 additions & 0 deletions R/misc.R
Expand Up @@ -113,3 +113,8 @@ str.units = function(object, ...) {
cat(paste0(" Units: ", unit_string))
str(drop_units(object), ...)
}

#' @export
unique.units <- function(x, incomparables = FALSE, ...) {
.as.units(NextMethod(), units(x))
}
5 changes: 5 additions & 0 deletions R/mixed.R
Expand Up @@ -142,3 +142,8 @@ Ops.mixed_units = function(e1, e2) {
ret = .as.mixed_units(ret)
ret
}

#' @export
unique.mixed_units <- function(x, incomparables = FALSE, ...) {
.as.mixed_units(NextMethod())
}
5 changes: 5 additions & 0 deletions tests/testthat/test_misc.R
Expand Up @@ -124,3 +124,8 @@ test_that("subsetting keeps pillar attribute (#275)", {
expect_equal(attr(x[1:2], "pillar"), "bar")
expect_equal(attr(x[[1]], "pillar"), "bar")
})

test_that("unique.units works", {
x <- set_units(c(1, 1, 2, 3), kg)
expect_equal(unique(x), set_units(c(1, 2, 3), kg))
})
11 changes: 11 additions & 0 deletions tests/testthat/test_mixed.R
Expand Up @@ -56,3 +56,14 @@ test_that("order is preserved", {

expect_equal(as.numeric(m), x / 1000)
})

test_that("unique.mixed_units works", {
x <- c(set_units(c(1, 1, 2), kg), set_units(c(4, 4, 5), s), allow_mixed = TRUE)
expect_equal(unique(x), c(set_units(c(1, 2), kg), set_units(c(4, 5), s), allow_mixed = TRUE))

y <- c(set_units(c(1, 1, 1), m/s), set_units(c(1, 1, 1), kg/s), allow_mixed = TRUE)
expect_equal(unique(y), c(set_units(1, m/s), set_units(1, kg/s), allow_mixed = TRUE))

z <- c(set_units(c(1, 2), kg), set_units(c(3, 4), s), set_units(c(2, 3), kg), allow_mixed = TRUE)
expect_equal(unique(z), c(set_units(c(1, 2), kg), set_units(c(3, 4), s), set_units(3, kg), allow_mixed = TRUE))
})

0 comments on commit 00f23ac

Please sign in to comment.