r-quantities / units

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

Child class of units #241

Closed vorpalvorpal closed 4 years ago

vorpalvorpal commented 4 years ago

I'm trying to make a child class of "units", but am not making much headway. I can get something sort of functional by writing:

set_myclass <- function(value, units, other_junk =NA){
# do some stuff
units <- structure(units, numerator = numerator, denominator = denominator, class = "symbolic_units")
structure(value, units=units, other_junk = NA, class = c("units", "myclass"))}

This prints correctly, and allows me to do addition provided the units are the same, but I can't do multiplication, division, etc. I'm guessing my approach is totally wrong, but I can't figure out what the correct approach is. I've played around with using set_units and as_units in the class function definition, but that hasn't helped much.

edzer commented 4 years ago

If you want to subclass an existing class, the subclass name should come first, as in

structure(value, units=units, other_junk = NA, class = c("myclass", "units"))}
Enchufa2 commented 4 years ago

You can check what the {quantities} package does, which is a subclass of {units} and {errors} in a sort of low-cost multi-inheritance.

vorpalvorpal commented 4 years ago

Thank you, changing the order did the trick. I feel rather stupid now.

For anyone who finds this through google, this works:

set_measR <- function(value, unit=NA, error=NA, method=NA, LRL=NA, URL=NA, lowerRange=0, upperRange=Inf){
  qValue <- parse_quantities(value) # makes quantities, units and errors object
  # do stuff
  structure(qValue, instrumentalValue = instrumentalValue, LRL = LRL, URL = URL, lowerRange = lowerRange, upperRange = upperRange, method = method, class = c("measR", "quantities", "units", "errors"))
} 

And thank you for pointing out that quantities package. It does about half of what I was trying to do, but much better than I would have been able to do it!