From jmc at r-project.org  Sun Mar 25 01:00:01 2007
From: jmc at r-project.org (John Chambers)
Date: Sat, 24 Mar 2007 17:00:01 -0700
Subject: [Rd] substitute and S4 objects
In-Reply-To: <44dc13910703231540g5ade432en6b0911e31434bb7c@mail.gmail.com>
References: <44dc13910703231540g5ade432en6b0911e31434bb7c@mail.gmail.com>
Message-ID: <4605BB81.2050400@r-project.org>

First, by "doesn't work" you mean the printed output.  The value 
returned is the same.

Second, the problem is not a general one with S4 methods but with 
primitive functions.  To see this, define a real function with a similar 
method:

 > setGeneric("foo", function(e1, e2) standardGeneric("foo"))
[1] "foo"

 > setMethod("foo", "num", function(e1, e2) {
    cat("Computing\n", deparse(substitute(e1)), "+", 
deparse(substitute(e2)),
        "\n")
    e1 at x + e2@ x
})

[1] "foo"
 > foo(a,b)
Computing
 a + b
[1] 1.8

The problem with primitives, such as `+`, is that they aren't called in 
the way functions are normally called.  If my understanding is correct, 
substitute() with one argument uses the "promise" objects corresponding 
to the formal arguments in order to extract the unevaluated expression.  
There are no such things with primitives.

I think you need to use a different function for whatever you really wanted.

Franck Arnaud wrote:
> Hi all,
> I don't understand why this does not what I expect :
>
> ## code start here ##############
> setClass("num",representation(x="numeric"))
>
> num<-function(x) new("num",x=x)
>
> add<-function(e1,e2) {
>     cat("Computing
> ",deparse(substitute(e1)),"+",deparse(substitute(e2)),"\n")
>     e1 at x+e2@x
> }
>
> setMethod("+","num",function(e1,e2) {
>     cat("Computing
> ",deparse(substitute(e1)),"+",deparse(substitute(e2)),"\n")
>     e1 at x+e2@x
> })
>
>
> a<-num(3.2)
> b<-num(-1.4)
>
> add(a,b)
> a+b
> ## code ends here ##############
>
> a+b does not work : I would like that add(a,b) and a+b give the exact same
> result
> I've seen a post on R-devel, but the answer seemed not to apply here.
> I've tried to use deparse(substitute(e1,sys.frame (-1))) and
> deparse(substitute(e1,sys.frame(-2))) (as it was advised by GG in january
> 2006). But it did not work.
>
> Therefore, i'm looking for 1) an explanation for this phenomenon (link to a
> doc, anything) and/or 2) a way to do what i want, if it is possible.
>
> Thanks a lot
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>



[Rd] substitute and S4 objects
John Chambers