How to adjust group generics Ops() in R for a given s3 class?

39 Views Asked by At

As an exercise to get familiar with OOP in R I want to do the following: There is the units package that assigns units (e.g. "gramm" ,"meter" etc.) to numeric data. However the way Ops.units is implemented does not allow plus/minus Operations with non-units objects. This leads to compatibility issues with other packages. So my plan is to adjust it. I tried multiple things. First I tried to make a subclass units2 with its own Ops method that attached units if needed. However other methods of the units class return units objects instead of units2 objects. So after such an operation the units2 Ops method will no longer be used. The second approach is to overwrite Ops.units. I tried it as follows:

library(units)
old_ops = function(e1,e2,.Generic) {}
body(old_ops) = body(units:::Ops.units)
Ops.units = function(e1,e2){
  

  e = list(e1,e2)
  is_unit = map_lgl(e, ~inherits(.x, "units"))
  if(!all(is_unit) & .Generic %in% c("+","-")){
    #if one of the elements is not a unit, assume the units of the other
    unit_element = e[is_unit][[1]]
    non_unit_element = e[!is_unit][[1]]
    non_unit_element  = set_units(non_unit_element,unit_element, mode = "standard")
    e1 = unit_element
    e2 = non_unit_element
  }
  old_ops(e1,e2,.Generic)
}

However old_ops needs amongst others the function .units.simplify which is not visible and thus returns an error. I could add it to the signature of old_ops and pass it as an argument via .units.simplify=units:::.units.simplify but this seems ugly.

Generally I think I may approaching it wrong. Any point in the right direction would be greatly appreciated!

0

There are 0 best solutions below