[Rd] Unexpected behaviour initializing S4 class

Krunoslav Sever sever at hsuhh.de
Tue Sep 1 12:10:57 CEST 2009


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.

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"
- 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



More information about the R-devel mailing list