r-quantities / units

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

unique() drops units #277

Closed ekatko1 closed 3 years ago

ekatko1 commented 3 years ago

set_units(5, g) %>% unique returns 5 would expect 5 g

Thanks :)

lewinfox commented 3 years ago

I've had a go at implementing unique.units() and unique.mixed_units(): see lewinfox/units/tree/unique-units.

After changes:

a <- set_units(c(1, 1, 2, 3), kg)
a
#> Units: [kg]
#> [1] 1 1 2 3

unique(a)
#> Units: [kg]
#> [1] 1 2 3

b <- c(set_units(c(1, 1, 2), kg), set_units(c(3, 3, 4), s), allow_mixed = TRUE)
b
#> Mixed units: kg (3), s (3) 
#> 1 [kg], 1 [kg], 2 [kg], 3 [s], 3 [s], 4 [s] 

unique(b)
#> Mixed units: kg (2), s (2) 
#> 1 [kg], 2 [kg], 3 [s], 4 [s]

Before I raise a PR I'd like some feedback on something that took me by surprise. If the mixed_units object is constructed with multiple "blocks" of the same unit then some of the ordering is preserved in the output of unique().

# The object has two "blocks" of `kg`
z <- c(set_units(c(1, 2), kg), set_units(c(3, 4), s), set_units(c(2, 3), kg), allow_mixed = TRUE)
z
#> Mixed units: kg (4), s (2) 
#> 1 [kg], 2 [kg], 3 [s], 4 [s], 2 [kg], 3 [kg] 

My current implementation gives

unique(z)
#> Mixed units: kg (3), s (2) 
#> 1 [kg], 2 [kg], 3 [s], 4 [s], 3 [kg] 

i.e. the result is not ordered by unit (the last 3 [kg] is off on its own). Is it desirable to have like units grouped together?

# Is this better?
unique(z)
#> Mixed units: kg (3), s (2) 
#> 1 [kg], 2 [kg], 3 [kg], 3 [s], 4 [s] 
Enchufa2 commented 3 years ago

Thanks, PR very welcome. :)

Before I raise a PR I'd like some feedback on something that took me by surprise. If the mixed_units object is constructed with multiple "blocks" of the same unit then some of the ordering is preserved in the output of unique().

Your current implementation is correct: order must be preserved.