r-quantities / units

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

`apply` on `units` matrix leads to loss of the `units` class #265

Closed michaeldorman closed 3 years ago

michaeldorman commented 3 years ago

When passing a units matrix to apply, the result loses the units class. For example:

library(units)

m = set_units(matrix(1:4,2,2), m/s)                                             
## Units: [m/s]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4 

apply(m, 1, min)                                                            
## [1] 1 2

It would be really convenient to keep the units, if possible, in colwise/rowwise operations just like in operations on the entire matrix:

min(m)                                                                      
## 1 [m/s]

Thank you very much!

Enchufa2 commented 3 years ago

Yeap, it would, but unfortunately there's not much we can do. This package works by implementing S3 methods for various generics. Functions like apply do not fall in that category, so we don't have any mechanism to make them preserve the attributes beyond wrapping them, which you can do for yourself, e.g.:

set_units(apply(m, 1, min), units(m), mode="standard")
michaeldorman commented 3 years ago

I understand. Thank you for the quick response and great package!