r-quantities / units

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

Hectares not treated as area #372

Closed hutchisonjtw closed 2 weeks ago

hutchisonjtw commented 2 months ago

Hi all, thanks for all of the work on this package, it's been very helpful for lots of spatial calculations that I use in my work. We often work with areas in hectares, and in the course of trying to buffer points to circles of known area, I discovered that the sqrt() function gives an error with areas in hectares:

x <- set_units(1, "ha")
sqrt(x)
Error in Ops.units(x, 0.5) : powers not divisible

Similarly, dividing ha by m results in ha/m, rather than just m:

> x/set_units(100, "m")
0.01 [ha/m]

Both works fine with m², so converting is an obvious and simple workaround:

y <- set_units(10000, "m2")
sqrt(y)
100 [m]
y/set_units(100, "m")
100 [m]

I know very little about the inner workings of the package so if it's non-trivial to fix then the workaround is fine, but as someone who regularly uses hectares for reporting it would be nice if the package was able to handle these without the extra lines of code. Thanks in advance!

Enchufa2 commented 2 months ago

It's... complicated. The way it works now is that we rely on udunits2 for conversions, but not for calculations. The reason is that udunits2 has an internal representation of magnitudes in fundamental units, and this is fine, because it allows it to know that the square root of 1 ha is 100 m (because, internally, when you set 1 ha, it's not 1 ha anymore but 10000 m^2). However, in this package we strive to keep the units you set, and only convert or simplify them if you request it. In other words, if we were to pass everything down to udunits2, then you wouldn't be able to print non-SI units at all.

So this is the reason why ha/m is not simplified or the square root of ha is not allowed: you need to explicitly request such conversions (to meters in this case) to be able to perform such operations.

Enchufa2 commented 2 weeks ago

Thanks again, closing here as expected behavior.