r-quantities / units

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

cbind and rbind silently drop units #311

Open billdenney opened 2 years ago

billdenney commented 2 years ago

cbind() and rbind() drop the units when combining with numeric or other units.

x <- units::set_units(c(1, 2), "g")
cbind(1, x)
#>        x
#> [1,] 1 1
#> [2,] 1 2
rbind(1, x)
#>   [,1] [,2]
#>      1    1
#> x    1    2
cbind(x, x)
#>      x x
#> [1,] 1 1
#> [2,] 2 2
rbind(x, x)
#>   [,1] [,2]
#> x    1    2
#> x    1    2

Created on 2022-03-09 by the reprex package (v2.0.1)

Enchufa2 commented 2 years ago

Thanks, we need to implement methods for them, as we have in errors and quantities.

billdenney commented 2 years ago

While implementing these, is it also possible to.implememt them for mixed_units? I ask for that one because I want to be able to do matrix multiplication for a linear regression, and having the units automatically carry through would be awesome!

edzer commented 2 years ago

I'm not sure we're already at the stage of handling matrices with mixed units; in any case the print method is odd,

> library(units)
udunits database from /usr/share/xml/udunits/udunits2.xml
> ?mixed_units
>      a <- 1:4
>      u <- c("m/s", "km/h", "mg/L", "g")
>      mixed_units(a, u)
Mixed units: g (1), km/h (1), m/s (1), mg/L (1) 
1 [m/s], 2 [km/h], 3 [mg/L], 4 [g] 
> m =     mixed_units(a, u)
> m
Mixed units: g (1), km/h (1), m/s (1), mg/L (1) 
1 [m/s], 2 [km/h], 3 [mg/L], 4 [g] 
> structure(m, dim = c(2,2))
Mixed units: g (1), km/h (1), m/s (1), mg/L (1) 
1 [m/s], 2 [km/h], 3 [mg/L], 4 [g] 
> str(structure(m, dim = c(2,2)))
Mixed units: g (1), km/h (1), m/s (1), mg/L (1) 
 $ : Units: [m/s] int 1
 $ : Units: [km/h] int 2
 $ : Units: [mg/L] int 3
 $ : Units: [g] int 4
 - attr(*, "dim")= int [1:2] 2 2
> class(structure(m, dim = c(2,2)))
[1] "mixed_units" "list"       

and as a "list-matrix" they won't work e.g. in matrix multiplication; also, as we found out earlier, we don't overload %*%.

Enchufa2 commented 2 years ago

I don't think this is the way of supporting regression with units either. Existing modelling functions work well and efficiently, and enabling units would require instead some wrapper, in a similar way as we explored and prototyped here for full quantities: https://r-spatial.org/r/2018/08/31/quantities-final.html#fitting-linear-models-with-quantities

billdenney commented 2 years ago

Thanks for the considerations on this and the pointer to the article about it. I also now see #226 which covers some other details about matrix multiplication. To keep things focused, I will continue the conversation about matrices over in the other issue. Though, thoughts on matrix structure that I will put there may also be relevant to the implementation of cbind() and rbind() here.