From mtmorgan at fhcrc.org  Tue Sep  1 13:43:21 2009
From: mtmorgan at fhcrc.org (Martin Morgan)
Date: Tue, 01 Sep 2009 04:43:21 -0700
Subject: [Rd] Unexpected behaviour initializing S4 class
In-Reply-To: <4A9CF331.6070404@hsuhh.de>
References: <4A9CF331.6070404@hsuhh.de>
Message-ID: <4A9D08D9.1060205@fhcrc.org>

Hi Kruno --

Krunoslav Sever wrote:
> Hello all!
> 
> I am not sure if this is known or even intended, but please consider the
> following simple example code:
> 
> # set up a simple S4 class with single slot
> setClass("b", representation = representation(x = "numeric"))
> 
> # provide initialize method
> setMethod("initialize",
>   signature(.Object = "b"),
>   function(.Object,...) b.initialize(.Object,...)
> )
> 
> # actual implementation of initialize method external
> b.initialize <- function(kl, x = numeric(),...) {
>   kl at x <- x
>   kl
> }
> 
> # this gives an error in R-2.9.2
> test <- new("b", x = 1:2, k = 3, y = 2)
> 
> What apparently happens is that the k=3 part in ... for b.initialize is
> assigned to kl while the initial "b" object that should be assigned to
> kl ends up in "..." of b.initialize.

This is R argument matching at work

> f <- function(.Object, ...) g(.Object, ...)
> g <- function(kl, x, ...) match.call()
> f(1, x=2, k=3)
g(kl = 3, x = 2, .Object)

specifically partial matching of named arguments taking precedence of
positional matching of unnamed arguments.

> I assume this is due to the naming similarity of k and kl, probably
> confusing the matching algorithm: if another first argument for
> b.initialize is used (not starting with k), everything is fine.
> 
> Other workarounds:
> - in setMethod write "kl = .Object" instead of simply ".Object"

yes, this avoids mixing matching by name and by position.

Martin Morgan

> - this does not happen if the contents of b.initialize are directly
> moved to the setMethod call, even if k is renamed to, say, .O
> This happened to me in a case where b is a subclass of another class
> which has a slot named k, so the "offending" k = 3 is not artificial here.
> 
> I hope some dev here can look into the switching effect: this cannot
> possibly be intended?
> 
> Here my sessioninfo():
>> sessionInfo()
> R version 2.9.2 (2009-08-24)
> i686-pc-linux-gnu
> 
> locale:
> LC_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC_COLLATE=de_DE.UTF-8;LC_MONETARY=C;LC_MESSAGES=de_DE.UTF-8;LC_PAPER=de_DE.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=de_DE.UTF-8;LC_IDENTIFICATION=C
> 
> 
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
> 
> Best
>   Kruno
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] Unexpected behaviour initializing S4 class
Martin Morgan