r-quantities / units

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

Mixed units when using a pipe operator #220

Closed LS31 closed 4 years ago

LS31 commented 4 years ago

I discovered the units package yesterday and I really like the idea of explicitly attributing units to data. I tried to incorporate it in a function, but ran into unexpected behaviour. When using a pipe operator the units seem to get mixed up.

library(magrittr)

calculate_bmi_A <- function(weight, height) {
  weight / ((height / 100) ^ 2) %>%
    units::set_units("kg1 m-2", mode = "standard")
}

calculate_bmi_B <- function(weight, height) {
  x = weight / ((height / 100) ^ 2)
  units::set_units(x, "kg1 m-2", mode = "standard")
}

calculate_bmi_A(120, 180)
#> 37.03704 [m^2/kg]
calculate_bmi_B(120, 180)
#> 37.03704 [kg/m^2]

I can not really say if this is related to issue https://github.com/r-quantities/units/issues/86

Is this expected behaviour and am I missing something? Or is it a bug? Thanks!

edzer commented 4 years ago

Looks like an operator precedence issue:

weight = 120; height = 180
> weight / ((height / 100) ^ 2) %>% units::set_units("kg1 m-2", mode = "standard")
37.03704 [m^2/kg]
> (weight / ((height / 100) ^ 2)) %>% units::set_units("kg1 m-2", mode = "standard")
37.03704 [kg/m^2]
LS31 commented 4 years ago

I see. So not a bug in units, but unexpected expected behaviour :) Thanks for the quick reply.