From whuber at embl.de  Mon Mar 15 21:21:24 2010
From: whuber at embl.de (Wolfgang Huber)
Date: Mon, 15 Mar 2010 21:21:24 +0100
Subject: [Rd] Strange behavior of assign in a S4 method.
In-Reply-To: <4B9E0CED.6030405@u-paris10.fr>
References: <4B9E0CED.6030405@u-paris10.fr>
Message-ID: <4B9E96C4.90209@embl.de>

Dear Christophe

type

showMethods("foo1", inc=TRUE)
showMethods("foo2", inc=TRUE)

to see the difference between the two functions, and this will explain 
their different behaviour. This feature of S4 has been discussed here 
many times before, see e.g.: 
http://tolstoy.newcastle.edu.au/R/e4/help/08/01/1676.html

Perhaps juggling with the 'n' argument of 'parent.frame' could help in 
hacking something together that 'works', but as far as I can see what 
you want to is an abuse of R's pass by value / functional language 
semantics.

For example, try these and check whether this results in what you intended:

foo2(3)
foo2(e+2)
sapply(1:5, foo2)
ls()

	Best wishes
	Wolfgang


Christophe Genolini scripsit 15/03/10 11:33:
> Hi the list,
> I define a method that want to change an object without assignation 
> (foo(x) and not x<-foo(x)) using deparse and assign.
> But when the argument of the method does not match *exactly* with the 
> definition of the generic function, assign does not work...
> Anything wrong?
> 
> Christophe
> 
> #------ Does not work ------#
> setGeneric("foo1",function(x,...){standardGeneric("foo1")})
> 
> setMethod(f="foo1",signature="numeric",definition=
>    function(x,y=1,...){
>        nameX<-deparse(substitute(x))
>        x <- x^2
>        assign(nameX,x,envir=parent.frame())
>    }
> )
> 
> e <- 3
> foo1(e,y=5)
> cat(e)
> 
> 
> #------ Does work ------#
> setGeneric("foo2",function(x,...){standardGeneric("foo2")})
> 
> setMethod(f="foo2",signature="numeric",definition=
>    function(x,...){
>        nameX<-deparse(substitute(x))
>        x <- x^2
>        assign(nameX,x,envir=parent.frame())
>    }
> )
> 
> e <- 3
> foo2(e,y=5)
> cat(e)
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



--
Wolfgang Huber
EMBL
http://www.embl.de/research/units/genome_biology/huber/contact



[Rd] Strange behavior of assign in a S4 method.
Wolfgang Huber