From mtmorgan at fhcrc.org  Sat Jun  4 15:41:05 2011
From: mtmorgan at fhcrc.org (Martin Morgan)
Date: Sat, 04 Jun 2011 06:41:05 -0700
Subject: [Rd] S4 class, passing argument names to function,
	modify original
In-Reply-To: <C6C4A88B-761A-46F0-90E3-24260973F699@uzh.ch>
References: <C6C4A88B-761A-46F0-90E3-24260973F699@uzh.ch>
Message-ID: <4DEA35F1.7020208@fhcrc.org>

On 06/04/2011 03:07 AM, soeren.vogel at uzh.ch wrote:
> Hello, an S4 class "Foo" is defined with a setter, $. For several reasons, the setter calls a function, .foo.update(). However, bypassing the argument names of the setter does not work. Question 1: Why not and how can I fix this? Question 2: What is the way to define either the function or the setter to modify the original object (not returning the modified copy of it an overwrite the original by assignment)? Thanks, S?ren
>
> setClass("Foo",
>    representation(
>      N = "numeric"
>    ),
>    prototype(
>      N = 10000
>    )
> )
>
> .foo.update<- function(object, ...) {
>    args<- list(...)
>    for (i in slotNames("Foo")[pmatch(names(args), slotNames("Foo"), nomatch=0)]) {
>      slot(object, i)<- args[[i]]
>      # indeed more to do here
>      return(object)
>    }
> }

Since names(args) is 'name', and 'name' is not a slot of 'Foo', the 
return of pmatch is 0 and .foo.update returns NULL. Put return(object) 
outside the for loop.

> setReplaceMethod("$", "Foo",
>    function(x, name, value) {
>      x<- .foo.update(x, name=value)

here your intention is that name=value to be substituted with N=99, but 
you end up with name=99. You could arrange to parse this correctly, but 
this isn't usually what you _want_ to do and I don't really understand 
what you're trying to accomplish. Maybe

.foo.update <- function(object, name, value, ...)
{
     slot(object, name) <- value
     ## some other stuff
     object
}

Hope that helps a bit.

Martin

>      x
>    }
> )
>
> x<- new("Foo")
> x
> x$N<- 99
> x # NULL????
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel


-- 
Computational Biology
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109

Location: M1-B861
Telephone: 206 667-2793



[Rd] S4 class, passing argument names to function, modify original
Martin Morgan