r-quantities / units

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

Allow vec_cast of numeric to units #303

Closed hughjonesd closed 2 years ago

hughjonesd commented 2 years ago

I've been working on integrating support for units into hughjonesd/santoku. I sometimes want to determine whether a units vector x is positive or not. For x > 0 to work, I need to either promote x to a numeric or promote 0 to the relevant unit. My ideal would be x > vec_cast(0, x), since this keeps the code generic. At the moment, this fails. Would it be reasonable to allow casting a numeric type to a non-mixed units variable?

Enchufa2 commented 2 years ago

Implementing such a method would mean that pivoting a data frame or binding rows could lead to silent binds between units and non-units vectors, and this is not something we want.

But how is this x > vec_cast(0, x) more generic than simply as.numeric(x) > 0?

hughjonesd commented 2 years ago

as.numeric(x) will often convert to NA, when it should error, e.g. as.numeric("foo"). My current workaround is to write my own strict_as_numeric() function.

Enchufa2 commented 2 years ago

I see. I still think that this is the best approach here. units treats plain numeric vectors as unitless quantities, and it has been the case for a number of years now. The reason is that you are able to do things like 2*set_units(1, m), which seems natural. Casting unitless to any other unit cannot be allowed, and thus this behaviour with comparisons. As I already said, this casting would allow row bindings with units and non-units objects with dplyr, and this breaks the unitless assumption.

Let us know if we could do something else to help you with this, but otherwise, we should close this.

hughjonesd commented 2 years ago

Yeah, I understand. I wonder if rlang would benefit from a stricter as_numeric() function.

Enchufa2 commented 2 years ago

Perfect, thanks for the discussion!