r-quantities / units

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

Get Ops.units to allow for non-units second argument #186

Closed kendonB closed 5 years ago

kendonB commented 5 years ago

Ops.units within summary.lm fails because var removes the units attribute.

library(units)
#> udunits system database from C:/R/Library/3.5/units/share/udunits
iris$Sepal.Length <- set_units(iris$Sepal.Length, "cm")

summary(lm(Sepal.Length ~ Sepal.Width,
           data = iris))
#> Error in Ops.units(mean(f)^2, var(f)): both operands of the expression should be "units" objects

Created on 2019-01-21 by the reprex package (v0.2.1.9000)

Enchufa2 commented 5 years ago

units is quite strict about what you can or can't do, and IMO this is the right way to go. Fitting a linear model is a quite complex task, with a lot of stuff going on under the hood, so this is just a symptom of a broader problem. We can't throw away a good design rule just to treat a symptom and move the issue to another place.

There is another more general approach (with issues of its own), which, as @edzer pointed out in r-devel, is discussed here.

kendonB commented 5 years ago

As @edzer said on r-devel, this particular problem is not solved by making var output a units object.

The next thing to fail is this line in summary.lm:

ans$adj.r.squared <- 1 - (1 - ans$r.squared) * ((n - 
  df.int)/rdf)

where Ops.units fails because ans$r.squared is of unit [1].

Enchufa2 commented 5 years ago

Right now, we have automatic conversion from numeric to unitless in some operations:

set_units(100, "m")^2
#> 10000 [m^2]
set_units(100, "m")*2
#> 200 [m]
set_units(100, "m")/2
#> 50 [m]

Maybe we could extend this to other operators (or at least to + and -)? What do you think, @edzer?