[R] questions about setMethod("Arith", ...)

Matthias Kohl Matthias.Kohl at uni-bayreuth.de
Tue Jul 6 13:17:28 CEST 2004


Hi,

we have some questions concerning the definition of new arithmetic methods.

In our package "distr" (on CRAN) we define some new arithmetic methods 
for "+", "-", "*", "/".
After loading "distr" the corresponding arithmetic methods work. Now, if 
we define a new
class and also a new method for one of the arithmetic methods "+", "-", 
"*", "/", still everything works fine. But, if we then define new 
methods for the whole group "Arith", the arithmetic methods of "distr" 
no longer work. (for more details see example code below)
What are we missing?

Moreover, there is a certain precendence; i.e., if one defines a single 
arithmetic method (e.g., "/") and alterwards defines a method for the 
whole group "Arith", the "old" method "/" remains valid. 
However, if we first define a method for the whole group "Arith" and 
afterwards define a new single arithmetic method (e.g., "+") the new one 
is valid. (for more details see example code below).
Is this intended?

Thanks for your help,
Matthias, Thomas

###########################################################
## Example code
###########################################################
require(distr)
getMethods("/")  # shows the corresponding methods of "distr"

## now define a new class "track" (see Chambers (1998))
## and define "/"

setClass("track", representation(x = "numeric", y = "numeric"))
setMethod("/", signature("track", "numeric"),
          function(e1, e2){ e1 at y = e1 at y/e2; e1 })

getMethods("/")  # shows the corresponding methods 
		 # of "distr" and class "track"

(N <- Norm()) # creates an object of standard normal distribution
(N1 <- N/3) # works
(tr <- new("track", x = 1:3, y = 4:6))
(tr1 <- tr/3) # works

## now define new methods for "Arith"
setMethod("Arith", signature("track", "numeric"),
          function(e1, e2){ 
	    e1 at x = callGeneric(e1 at x, e2)
	    e1
	  })

getMethods("/") # "/" for "distr" is lost
N2 <- N/3 # fails
(tr2 <- tr/3) # works, "but" still the "old" method
tr + 2 # works

## now a new method "+"
setMethod("+", signature("track", "numeric"),
          function(e1, e2){ e1 at y = e1 at y+e2; e1 })

tr + 2 # works, "but" with the "new" method




More information about the R-help mailing list