r-quantities / units

Measurement units for R
https://r-quantities.github.io/units
172 stars 27 forks source link

ifelse silently drops units #350

Closed ilikegitlab closed 11 months ago

ilikegitlab commented 11 months ago

It would be nice to add a method for base::ifelse to preserve units:

ifelse(T,set_units(1,"m"),set_units(1,"mm")) [1] 1

As a workaround, dplyr::if_else does preserve units, but adds package requirements and tends to evaluate all arguments (which is problematic in some cases).

Enchufa2 commented 11 months ago

Unfortunately, ifelse is not S3 standard generic, so we cannot implement a method. If you look into this function though, you'll see that internally it uses test as the base vector and then substitutes the matching elements from yes and no. This means that, if test has units, then the output will have units, but also that units for yes and no need to be compatible. Example:

library(units)
#> udunits database from /usr/share/udunits/udunits2.xml

ifelse(set_units(c(1, 0, 1, 0, 1), m), set_units(8, km), set_units(3, mm))
#> Units: [m]
#> [1] 8e+03 3e-03 8e+03 3e-03 8e+03
ilikegitlab commented 11 months ago

Thanks. this is a better workaround for me. Feel free to close if nothing more can be done from units side!