[Rd] cumsum method in Math group

Michael Lawrence lawrence.michael at gene.com
Thu Jun 9 14:34:36 CEST 2016


On Thu, Jun 9, 2016 at 1:13 AM, Edzer Pebesma
<edzer.pebesma at uni-muenster.de> wrote:
> When running
>
> a = runif(10)
> class(a) = "foo"
> Math.foo = function(x, ...) {
>     NextMethod(.Generic)
> }
> signif(a, 3)
> cumsum(a)
>
>
> I don't understand why cumsum strips the class, but signif does not.
> Both claim in the documentation that "These are generic functions:
> methods can be defined for them individually or via the ‘Math’ group
> generic."
>

There's no contract that the class be preserved. Only that dispatch
will happen. It's fairly unpredictable when R will preserve
attributes, like class. It's safest to cast the result in your Math
method. In general, who is to say whether the cumsum() of an object is
a valid instance of the same class? This also implies that, while
initially tempting, extending base types, in particular vector types,
will ultimately lead to unpredictable behavior and frustration.
Consider composition instead.

> --
> Edzer Pebesma
> Institute for Geoinformatics  (ifgi),  University of Münster
> Heisenbergstraße 2, 48149 Münster, Germany; +49 251 83 33081
> Journal of Statistical Software:   http://www.jstatsoft.org/
> Computers & Geosciences:   http://elsevier.com/locate/cageo/
> Spatial Statistics Society http://www.spatialstatistics.info
>
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



More information about the R-devel mailing list