[Rd] S4 method dispatch and namespaces: why is default method selected
michal2992 at gmail.com
Mon May 18 15:31:40 CEST 2009
I ran into the following peculiarity involving S4 method dispatch and
I develop a package which have a namespace and which depends on 'pixmap'
package, which itself does not have a namespace.
Now, in my package I have a class which has a slot for objects from
class "pixmap" and I
want to have a "plot" method for this new class. Not to clutter the point with
my original code here is a stylized example:
# library(pixmap) # so that the class pixmap is available
setClass("myclass", representation(img="pixmap", title="character",
# method to plot
setMethod("plot", signature(x="myclass", y="missing"),
function(x, main=x at title, ...)
# plot using the method from pixmap package
plot(x=x at img, ...)
points(seq(along=x at other), other)
Now, if you try to do this:
f <- system.file(file.path("pictures", "logo.ppm"), package="pixmap")
o <- new("myclass", img=read.pnm(f), title="some title", other=Inf)
# now this works as the plot method for signature x="pixmap" y="ANY" is
# dispatched correctly
However, when I put all these in a package with Depends field in
DESCRIPTION having: methods, pixmap, and with the following namespace:
things stop working (this is from package test):
> f <- system.file(file.path("pictures", "logo.ppm"), package="pixmap")
> o <- new("myclass", a=read.pnm(f), title="tytul")
Error in as.double(y) :
cannot coerce type 'S4' to vector of type 'double'
Calls: plot ... plot -> .local -> plot -> plot.default -> xy.coords
So apparently calling 'plot' dispatches the default method instead of using the
one from package 'pixmap'. Why?
As far as I understand the documentation and section 10.6 of "Software for Data
Analysis" the default method should never be selected as far as there are other
candidates. And there seems to be other candidates, and they seem to be properly
selected if checked using 'selectMethod' (this is from results from
Function: plot (package graphics)
> selectMethod("plot", signature(x="pixmap", y="missing"))
function (x, y, ...)
.local <- function (x, y, xlab = "", ylab = "", axes = FALSE,
asp = 1, ...)
x = as(x, "pixmapIndexed")
X <- seq(x at bbox, x at bbox, by = x at cellres)
Y <- seq(x at bbox, x at bbox, by = x at cellres)
image(x = X, y = Y, z = t(x at index[nrow(x at index):1, ,
drop = FALSE]), col = x at col, xlab = xlab, ylab = ylab,
axes = axes, asp = asp, ...)
.local(x, y, ...)
target "pixmap" "missing"
defined "pixmap" "ANY"
R version 2.9.0 (2009-04-17)
attached base packages:
 stats graphics grDevices utils datasets methods base
other attached packages:
loaded via a namespace (and not attached):
Thanks in advance!
More information about the R-devel