cumsum method in Math group

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

cumsum method in Math group

Edzer Pebesma
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."

--
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


______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

signature.asc (501 bytes) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: cumsum method in Math group

Michael Lawrence-3
On Thu, Jun 9, 2016 at 1:13 AM, Edzer Pebesma
<[hidden email]> 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
>
>
> ______________________________________________
> [hidden email] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel