Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow ud_convert() to work with class "difftime" (fix for #3012) #3168

Merged
merged 10 commits into from
Jun 8, 2023
Merged
12 changes: 9 additions & 3 deletions base/utils/R/ud_convert.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@
##' Unit conversion to replace the now-unmaintained `udunits2::ud.convert`
##' @author Chris Black
##'
##' @param x numeric vector
##' @param u1 string parseable as the units in which `x` is provided
##' @param x vector of class "numeric" or "difftime"
##' @param u1 string parseable as the units in which `x` is provided. If `x` is
##' class "difftime", then `u1` is not actually used. However, it still needs
##' to be supplied and needs to be convertible to `u2` for consistency.
##' @param u2 string parseable as the units to convert to
##'
##' @return numeric vector with values converted to units in `u2`
##' @export
ud_convert <- function(x, u1, u2) {
stopifnot(units::ud_are_convertible(u1, u2))
x1 <- units::set_units(x, value = u1, mode = "standard")
if(inherits(x, "difftime")) {
x1 <- units::as_units(x)
Aariq marked this conversation as resolved.
Show resolved Hide resolved
} else {
x1 <- units::set_units(x, value = u1, mode = "standard")
}
x2 <- units::set_units(x1, value = u2, mode = "standard")

units::drop_units(x2)
Expand Down
6 changes: 4 additions & 2 deletions base/utils/man/ud_convert.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions base/utils/tests/testthat/test-ud_convert.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,14 @@ test_that("output is type numeric and not class \"units\"", {
testthat::expect_type(x, "double")

})

test_that("ud_convert() handles difftime", {
x <- ud_convert(as.difftime("12:00:00"), u1 = "hours", u2 = "days")
testthat::expect_is(x, "numeric")
testthat::expect_equal(x, 0.5)

#u1 doesn't matter, except that it has to be convertible to u2
y <- ud_convert(as.difftime("12:00:00"), u1 = "years", u2 = "minutes")
testthat::expect_equal(y, 720)
expect_error(ud_convert(as.difftime("12:00:00"), u1 = "kilograms", u2 = "minutes"))
})