Re: [Rd] S4 class, passing argument names to function, modify original

From: Martin Morgan <mtmorgan_at_fhcrc.org>
Date: Sat, 04 Jun 2011 06:41:05 -0700

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

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Sat 04 Jun 2011 - 13:50:11 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 04 Jun 2011 - 15:30:15 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive