reg-S4.Rout.save 27.7 KB
Newer Older
1

2 3
R Under development (unstable) (2012-03-08 r58640)
Copyright (C) 2012 The R Foundation for Statistical Computing
4
ISBN 3-900051-07-0
5
Platform: x86_64-apple-darwin10.8.0/x86_64 (64-bit)
6 7 8 9 10 11 12 13 14 15

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
16
'help.start()' for an HTML browser interface to help.
17 18
Type 'q()' to quit R.

19
> ####--- S4 Methods (and Classes)  --- see also ../src/library/methods/tests/
20
> options(useFancyQuotes=FALSE)
21
> require(methods)
22
> ##too fragile: showMethods(where = "package:methods")
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
> 
> ##-- S4 classes with S3 slots [moved from ./reg-tests-1.R]
> setClass("test1", representation(date="POSIXct"))
> x <- new("test1", date=as.POSIXct("2003-10-09"))
> stopifnot(format(x @ date) == "2003-10-09")
> ## line 2 failed in 1.8.0 because of an extraneous space in "%in%"
> 
> stopifnot(all.equal(3:3, 3.), all.equal(1., 1:1))
> 
> ## trace (requiring methods):
> f <- function(x, y) { c(x,y)}
> xy <- 0
> trace(f, quote(x <- c(1, x)), exit = quote(xy <<- x), print = FALSE)
[1] "f"
> fxy <- f(2,3)
> stopifnot(identical(fxy, c(1,2,3)))
> stopifnot(identical(xy, c(1,2)))
> untrace(f)
> 
> ## a generic and its methods
> 
> setGeneric("f")
[1] "f"
> setMethod("f", c("character", "character"), function(x,	 y) paste(x,y))
[1] "f"
> 
> ## trace the generic
> trace("f", quote(x <- c("A", x)), exit = quote(xy <<- c(x, "Z")), print = FALSE)
[1] "f"
> 
> ## should work for any method
> 
> stopifnot(identical(f(4,5), c("A",4,5)),
+           identical(xy, c("A", 4, "Z")))
> 
> stopifnot(identical(f("B", "C"), paste(c("A","B"), "C")),
+           identical(xy, c("A", "B", "Z")))
> 
> ## trace a method
> trace("f", sig = c("character", "character"), quote(x <- c(x, "D")),
+       exit = quote(xy <<- xyy <<- c(x, "W")), print = FALSE)
[1] "f"
> 
> stopifnot(identical(f("B", "C"), paste(c("A","B","D"), "C")))
67 68
> stopifnot(identical(xyy, c("A", "B", "D", "W")))
> # got broken by Luke's lexical scoping fix:
69 70 71 72 73 74 75 76 77 78 79 80
> #stopifnot(identical(xy, xyy))
> 
> ## but the default method is unchanged
> stopifnot(identical(f(4,5), c("A",4,5)),
+           identical(xy, c("A", 4, "Z")))
> 
> removeGeneric("f")
[1] TRUE
> ## end of moved from trace.Rd
> 
> 
> ## print/show dispatch  [moved from  ./reg-tests-2.R ]
81 82 83 84 85
> ## The results  have waffled back and forth.
> ## Currently (R 2.4.0) the intent is that automatic printing of S4
> ## objects should correspond to a call to show(), as per the green
> ## book, p. 332.  Therefore, the show() method is called, once defined,
> ## for auto-printing foo, regardless of the S3 or S4 print() method.
86 87
> ## (But most of this example is irrelevant if one avoids S3 methods for
> ## S4 classes, as one should.)
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
> setClass("bar", representation(a="numeric"))
> foo <- new("bar", a=pi)
> foo
An object of class "bar"
Slot "a":
[1] 3.141593

> show(foo)
An object of class "bar"
Slot "a":
[1] 3.141593

> print(foo)
An object of class "bar"
Slot "a":
[1] 3.141593

> 
> setMethod("show", "bar", function(object){cat("show method\n")})
[1] "show"
> show(foo)
show method
> foo
show method
> print(foo)
show method
114 115 116
> # suppressed because output depends on current choice of S4 type or
> # not.  Can reinstate when S4 type is obligatory
> # print(foo, digits = 4)
117
> 
118 119 120 121 122
> ## DON'T DO THIS:  S3 methods for S4 classes are a design error JMC iii.9.09
> ## print.bar <- function(x, ...) cat("print method\n")
> ## foo
> ## print(foo)
> ## show(foo)
123 124
> 
> setMethod("print", "bar", function(x, ...){cat("S4 print method\n")})
125
Creating a generic function for 'print' from package 'base' in the global environment
126 127
[1] "print"
> foo
128
show method
129 130 131 132
> print(foo)
S4 print method
> show(foo)
show method
133 134 135
> ## calling print() with more than one argument suppresses the show()
> ## method, largely to prevent an infinite loop if there is in fact no
> ## show() method for this class.  A better solution would be desirable.
136 137 138 139 140 141 142 143 144 145 146 147 148 149
> print(foo, digits = 4)
S4 print method
> 
> setClassUnion("integer or NULL", members = c("integer","NULL"))
> setClass("c1", representation(x = "integer", code = "integer or NULL"))
> nc <- new("c1", x = 1:2)
> str(nc)# gave ^ANULL^A in 2.0.0
Formal class 'c1' [package ".GlobalEnv"] with 2 slots
  ..@ x   : int [1:2] 1 2
  ..@ code: NULL
> ##
> 
> 
> library(stats4)
150 151 152 153 154 155 156
> showMethods("coerce", classes=c("matrix", "numeric"))
Function: coerce (package methods)
from="ANY", to="matrix"
from="ANY", to="numeric"

> ## {gave wrong result for a while in R 2.4.0}
> 
157 158 159 160 161 162 163 164 165 166 167 168
> ## the following showMethods() output tends to generate errors in the tests
> ## whenever the contents of the packages change. Searching in the
> ## diff's can easily mask real problems.  If there is a point
> ## to the printout, e.g., to verify that certain methods exist,
> ## hasMethod() would be a useful replacement
> 
> ## showMethods(where = "package:stats4")
> ## showMethods("show")
> ## showMethods("show")
> ## showMethods("plot") # (ANY,ANY) and (profile.mle, missing)
> ## showMethods(classes="mle")
> ## showMethods(classes="matrix")
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
> 
> 
> ##--- "[" fiasco before R 2.2.0 :
> d2 <- data.frame(b= I(matrix(1:6,3,2)))
> ## all is well:
> d2[2,]
     [,1] [,2]
[1,]    2    5
> stopifnot(identical(d2[-1,], d2[2:3,]))
> ## Now make "[" into S4 generic by defining a trivial method
> setClass("Mat", representation(Dim = "integer", "VIRTUAL"))
> setMethod("[", signature(x = "Mat",
+ 			 i = "missing", j = "missing", drop = "ANY"),
+ 	  function (x, i, j, drop) x)
[1] "["
> ## Can even remove the method: it doesn't help
> removeMethod("[", signature(x = "Mat",
+                             i = "missing", j = "missing", drop = "ANY"))
[1] TRUE
> d2[1:2,] ## used to fail badly; now okay
     [,1] [,2]
[1,]    1    4
[2,]    2    5
> stopifnot(identical(d2[-1,], d2[2:3,]))
> ## failed in R <= 2.1.x
> 
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
> 
> ## Fritz' S4 "odditiy"
> setClass("X", representation(bar="numeric"))
> setClass("Y", contains="X")
> ## Now we define a generic foo() and two different methods for "X" and
> ## "Y" objects for arg missing:
> setGeneric("foo", function(object, arg) standardGeneric("foo"))
[1] "foo"
> setMethod("foo", signature(object= "X", arg="missing"),
+           function(object, arg) cat("an X object with bar =", object@bar, "\n"))
[1] "foo"
> setMethod("foo", signature(object= "Y", arg="missing"),
+           function(object, arg) cat("a Y object with bar =", object@bar, "\n"))
[1] "foo"
> ## Finally we create a method where arg is "logical" only for class
> ## "X", hence class "Y" should inherit that:
> setMethod("foo", signature(object= "X", arg= "logical"),
+           function(object, arg) cat("Hello World!\n") )
[1] "foo"
> ## now create objects and call methods:
> y <- new("Y", bar=2)
216
> ## showMethods("foo")
217 218 219 220 221
> foo(y)
a Y object with bar = 2 
> foo(y, arg=TRUE)## Hello World!
Hello World!
> ## OK, inheritance worked, and we have
222
> ## showMethods("foo")
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
> foo(y)
a Y object with bar = 2 
> ## still 'Y' -- was 'X object' in R < 2.3
> 
> 
> ## Multiple inheritance
> setClass("A", representation(x = "numeric"))
> setClass("B", representation(y = "character"))
> setClass("C", contains = c("A", "B"), representation(z = "logical"))
> new("C")
An object of class "C"
Slot "z":
logical(0)

Slot "x":
numeric(0)

Slot "y":
character(0)

> setClass("C", contains = c("A", "B"), representation(z = "logical"),
+          prototype = prototype(x = 1.5, y = "test", z = TRUE))
> (cc <- new("C"))
An object of class "C"
Slot "z":
[1] TRUE

Slot "x":
[1] 1.5

Slot "y":
[1] "test"

> ## failed reconcilePropertiesAndPrototype(..) after svn r37018
257 258
> stopifnot(identical(selectSuperClasses("C", dropVirtual = TRUE), c("A", "B")),
+ 	  0 == length(.selectSuperClasses(getClass("B")@contains)))
259
> 
260 261 262 263 264 265 266 267 268 269 270 271 272
> ## "Logic" group -- was missing in R <= 2.4.0
> stopifnot(all(getGroupMembers("Logic") %in% c("&", "|")),
+ 	  any(getGroupMembers("Ops") == "Logic"))
> setClass("brob", contains="numeric")
> b <- new("brob", 3.14)
> logic.brob.error <- function(nm)
+     stop("logic operator '", nm, "' not applicable to brobs")
> logic2 <- function(e1,e2) logic.brob.error(.Generic)
> setMethod("Logic", signature("brob", "ANY"), logic2)
[1] "Logic"
> setMethod("Logic", signature("ANY", "brob"), logic2)
[1] "Logic"
> ## Now ensure that using group members gives error:
273 274 275 276 277 278 279 280 281
> assertError <- function(expr)
+     stopifnot(inherits(try(expr, silent = TRUE), "try-error"))
> assertWarning <- function(expr)
+     stopifnot(inherits(tryCatch(expr, warning = function(w)w), "warning"))
> assertWarning_atleast <- function(expr) {
+     r <- tryCatch(expr, warning = function(w)w, error = function(e)e)
+     stopifnot(inherits(r, "warning") || inherits(r, "error"))
+ }
> 
282
> assertError(b & b)
283 284
Note: Method with signature "brob#ANY" chosen for function "&",
 target signature "brob#brob".
285
 "ANY#brob" would also be valid
286 287 288
> assertError(b | 1)
> assertError(TRUE & b)
> 
289
> 
290
> ## methods' hidden cbind() / rbind:
291
> cBind <- methods:::cbind
292 293 294 295
> setClass("myMat", representation(x = "numeric"))
> setMethod("cbind2", signature(x = "myMat", y = "missing"), function(x,y) x)
[1] "cbind2"
> m <- new("myMat", x = c(1, pi))
296
> stopifnot(identical(m, cBind(m)))
297
> 
298 299 300 301 302 303 304 305 306 307 308
> 
> ## explicit print or show on a basic class with an S4 bit
> ## caused infinite recursion
> setClass("Foo", representation(name="character"), contains="matrix")
> (f <- new("Foo", name="Sam", matrix()))
An object of class "Foo"
     [,1]
[1,]   NA
Slot "name":
[1] "Sam"

309
> f2 <- new("Foo", .Data = diag(2), name="Diag")# explicit .Data
310 311 312
> (m <- as(f, "matrix"))
     [,1]
[1,]   NA
313 314
> ## this has no longer (2.7.0) an S4 bit: set it explicitly just for testing:
> stopifnot(isS4(m. <- asS4(m)),
315 316
+           identical(m, f@.Data),
+ 	  .hasSlot(f, "name"))# failed in R <= 2.13.1
317
> show(m.)
318 319
     [,1]
[1,]   NA
320
> print(m.)
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
     [,1]
[1,]   NA
> ## fixed in 2.5.0 patched
> 
> ## callGeneric inside a method with new arguments {hence using .local()}:
> setGeneric("Gfun", function(x, ...) standardGeneric("Gfun"),
+ 	   useAsDefault = function(x, ...) sum(x, ...))
[1] "Gfun"
> setClass("myMat", contains="matrix")
> setClass("mmat2", contains="matrix")
> setClass("mmat3", contains="mmat2")
> setMethod(Gfun, signature(x = "myMat"),
+ 	  function(x, extrarg = TRUE) {
+ 	      cat("in 'myMat' method for 'Gfun() : extrarg=", extrarg, "\n")
+ 	      Gfun(unclass(x))
+ 	  })
[1] "Gfun"
attr(,"package")
[1] ".GlobalEnv"
> setMethod(Gfun, signature(x = "mmat2"),
+ 	  function(x, extrarg = TRUE) {
+ 	      cat("in 'mmat2' method for 'Gfun() : extrarg=", extrarg, "\n")
+ 	      x <- unclass(x)
+ 	      callGeneric()
+ 	  })
[1] "Gfun"
attr(,"package")
[1] ".GlobalEnv"
> setMethod(Gfun, signature(x = "mmat3"),
+ 	  function(x, extrarg = TRUE) {
+ 	      cat("in 'mmat3' method for 'Gfun() : extrarg=", extrarg, "\n")
+ 	      x <- as(x, "mmat2")
+ 	      callGeneric()
+ 	  })
[1] "Gfun"
attr(,"package")
[1] ".GlobalEnv"
358 359 360 361 362
> wrapG <- function(x, a1, a2) {
+     myextra <- missing(a1) && missing(a2)
+     Gfun(x, extrarg = myextra)
+ }
> 
363 364 365 366 367 368 369 370 371
> (mm <- new("myMat", diag(3)))
An object of class "myMat"
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1
> Gfun(mm)
in 'myMat' method for 'Gfun() : extrarg= TRUE 
[1] 3
372 373 374 375 376 377 378
> stopifnot(identical(wrapG(mm),    Gfun(mm, TRUE)),
+           identical(wrapG(mm,,2), Gfun(mm, FALSE)))
in 'myMat' method for 'Gfun() : extrarg= TRUE 
in 'myMat' method for 'Gfun() : extrarg= TRUE 
in 'myMat' method for 'Gfun() : extrarg= FALSE 
in 'myMat' method for 'Gfun() : extrarg= FALSE 
> 
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
> Gfun(mm, extrarg = FALSE)
in 'myMat' method for 'Gfun() : extrarg= FALSE 
[1] 3
> m2 <- new("mmat2", diag(3))
> Gfun(m2)
in 'mmat2' method for 'Gfun() : extrarg= TRUE 
[1] 3
> Gfun(m2, extrarg = FALSE)
in 'mmat2' method for 'Gfun() : extrarg= FALSE 
[1] 3
> ## The last two gave Error ...... variable ".local" was not found
> (m3 <- new("mmat3", diag(3)))
An object of class "mmat3"
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1
> Gfun(m3)
in 'mmat3' method for 'Gfun() : extrarg= TRUE 
in 'mmat2' method for 'Gfun() : extrarg= TRUE 
[1] 3
> Gfun(m3, extrarg = FALSE) # used to not pass 'extrarg'
in 'mmat3' method for 'Gfun() : extrarg= FALSE 
in 'mmat2' method for 'Gfun() : extrarg= FALSE 
[1] 3
> 
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
> ## -- a variant of the above which failed in version <= 2.5.1 :
> setGeneric("Gf", function(x, ...) standardGeneric("Gf"))
[1] "Gf"
> setMethod(Gf, signature(x = "mmat2"),
+           function(x, ...) {
+               cat("in 'mmat2' method for 'Gf()\n")
+               x <- unclass(x)
+               callGeneric()
+           })
[1] "Gf"
attr(,"package")
[1] ".GlobalEnv"
> setMethod(Gf, signature(x = "mmat3"),
+           function(x, ...) {
+               cat("in 'mmat3' method for 'Gf()\n")
+               x <- as(x, "mmat2")
+               callGeneric()
+           })
[1] "Gf"
attr(,"package")
[1] ".GlobalEnv"
> setMethod(Gf, signature(x = "matrix"),
+ 	  function(x, a1, ...) {
+               cat(sprintf("matrix %d x %d ...\n", nrow(x), ncol(x)))
+               list(x=x, a1=a1, ...)
+           })
[1] "Gf"
attr(,"package")
[1] ".GlobalEnv"
> 
> wrap2 <- function(x, a1, ...) {
+     A1 <- if(missing(a1)) "A1" else as.character(a1)
+     Gf(x, ..., a1 = A1)
+ }
> ## Gave errors in R 2.5.1 :
> wrap2(m2, foo = 3.14)
in 'mmat2' method for 'Gf()
matrix 3 x 3 ...
$x
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

$a1
[1] "A1"

$foo
[1] 3.14

> wrap2(m2, 10, answer.all = 42)
in 'mmat2' method for 'Gf()
matrix 3 x 3 ...
$x
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

$a1
[1] "10"

$answer.all
[1] 42

> 
> 
> ## regression tests of dispatch: most of these became primitive in 2.6.0
> setClass("c1", "numeric")
> setClass("c2", "numeric")
> x_c1 <- new("c1")
> # the next failed < 2.5.0 as the signature in .BasicFunsList was wrong
> setMethod("as.character", "c1", function(x, ...) "fn test")
[1] "as.character"
> as.character(x_c1)
[1] "fn test"
> 
> setMethod("as.integer", "c1", function(x, ...) 42)
[1] "as.integer"
> as.integer(x_c1)
[1] 42
> 
> setMethod("as.logical", "c1", function(x, ...) NA)
[1] "as.logical"
> as.logical(x_c1)
[1] NA
> 
> setMethod("as.complex", "c1", function(x, ...) pi+0i)
[1] "as.complex"
> as.complex(x_c1)
[1] 3.141593+0i
> 
> setMethod("as.raw", "c1", function(x) as.raw(10))
[1] "as.raw"
> as.raw(x_c1)
[1] 0a
> 
502
> # as.double, as.real use as.numeric for their methods to maintain equivalence
503 504
> setMethod("as.numeric", "c1", function(x, ...) 42+pi)
[1] "as.numeric"
505 506
> identical(as.numeric(x_c1),as.double(x_c1))
[1] TRUE
507 508
> identical(as.numeric(x_c1),as.real(x_c1))
[1] TRUE
509
> 
510 511 512 513
> 
> setMethod(as.double, "c2", function(x, ...) x@.Data+pi)
[1] "as.numeric"
> x_c2 <- new("c2", pi)
514 515
> identical(as.numeric(x_c2),as.double(x_c2))
[1] TRUE
516 517
> identical(as.numeric(x_c2),as.real(x_c2))
[1] TRUE
518 519 520 521 522 523
> 
> ## '!' changed signature from 'e1' to 'x' in 2.6.0
> setClass("foo", "logical")
> setMethod("!", "foo", function(e1) e1+NA)
[1] "!"
Warning message:
524
For function '!', signature "foo": argument in method definition changed from (e1) to (x) 
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
> selectMethod("!", "foo")
Method Definition:

function (x) 
x + NA

Signatures:
        x    
target  "foo"
defined "foo"
> xx <- new("foo", FALSE)
> !xx
An object of class "foo"
[1] NA
> 
540 541 542
> ## This failed for about one day -- as.vector(x, mode) :
> setMethod("as.vector", signature(x = "foo", mode = "missing"),
+           function(x) unclass(x))
543
Creating a generic function for 'as.vector' from package 'base' in the global environment
544 545
[1] "as.vector"
> ## whereas this fails in R versions earlier than 2.6.0:
546
> setMethod("as.vector", "foo", function(x) unclass(x))
547
[1] "as.vector"
548
> stopifnot(removeClass("foo"))
549
> 
550 551 552 553 554 555 556 557 558 559 560
> ## stats4::AIC in R < 2.7.0 used to clobber stats::AIC
> pfit <- function(data) {
+     m <- mean(data)
+     loglik <- sum(dpois(data, m))
+     ans <- list(par = m, loglik = loglik)
+     class(ans) <- "pfit"
+     ans
+ }
> AIC.pfit <- function(object, ..., k = 2) -2*object$loglik + k
> AIC(pfit(1:10))
[1] 0.05867604
561
> library(stats4) # and keep on search() for tests below
562 563 564 565 566 567 568 569 570 571 572 573
> AIC(pfit(1:10)) # failed in R < 2.7.0
[1] 0.05867604
> 
> ## For a few days (~ 2008-01-30), this failed to work without any notice:
> setClass("Mat",  representation(Dim = "integer","VIRTUAL"))
> setClass("dMat", representation(x = "numeric",  "VIRTUAL"), contains = "Mat")
> setClass("CMat", representation(dnames = "list","VIRTUAL"), contains = "Mat")
> setClass("dCMat", contains = c("dMat", "CMat"))
> stopifnot(!isVirtualClass("dCMat"),
+ 	  length(slotNames(new("dCMat"))) == 3)
> 
> 
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
> ## Passing "..." arguments in nested callGeneric()s
> setClass("m1", contains="matrix")
> setClass("m2", contains="m1")
> setClass("m3", contains="m2")
> ##
> setGeneric("foo", function(x, ...) standardGeneric("foo"))
[1] "foo"
> setMethod("foo", signature(x = "m1"),
+ 	  function(x, ...) cat(" <m1> ", format(match.call()),"\n"))
[1] "foo"
> setMethod("foo", signature(x = "m2"),
+ 	  function(x, ...) {
+ 	      cat(" <m2> ", format(match.call()),"\n")
+ 	      x <- as(x, "m1"); callGeneric()
+ 	  })
[1] "foo"
> setMethod("foo", signature(x = "m3"),
+ 	  function(x, ...) {
+ 	      cat(" <m3> ", format(match.call()),"\n")
+ 	      x <- as(x, "m2"); callGeneric()
+ 	  })
[1] "foo"
> foo(new("m1"), bla = TRUE)
 <m1>  foo(x = new("m1"), bla = TRUE) 
> foo(new("m2"), bla = TRUE)
 <m2>  foo(x = new("m2"), bla = TRUE) 
 <m1>  foo(x = x, bla = TRUE) 
> foo(new("m3"), bla = TRUE)
 <m3>  foo(x = new("m3"), bla = TRUE) 
 <m2>  foo(x = x, bla = TRUE) 
 <m1>  foo(x = x, bla = TRUE) 
> ## The last one used to loose 'bla = TRUE' {the "..."} when it got to m1
> 
> ## is() for S3 objects with multiple class strings
> setClassUnion("OptionalPOSIXct",   c("POSIXct",   "NULL"))
> stopifnot(is(Sys.time(), "OptionalPOSIXct"))
> ## failed in R 2.7.0
> 
> ## getGeneric() / getGenerics() "problems" related to 'tools' usage:
> e4 <- as.environment("package:stats4")
> gg4 <- getGenerics(e4)
> stopifnot(c("BIC", "coef", "confint", "logLik", "plot", "profile",
+             "show", "summary", "update", "vcov") %in% gg4, # %in% : "future proof"
+           unlist(lapply(gg4, function(g) !is.null(getGeneric(g, where = e4)))),
+           unlist(lapply(gg4, function(g) !is.null(getGeneric(g)))))
> em <- as.environment("package:methods")
> ggm <- getGenerics(em)
> gms <- c("addNextMethod", "body<-", "cbind2", "initialize",
622
+ 	 "loadMethod", "Ops", "rbind2", "show")
623 624 625 626 627 628 629
> stopifnot(unlist(lapply(ggm, function(g) !is.null(getGeneric(g, where = em)))),
+ 	  unlist(lapply(ggm, function(g) !is.null(getGeneric(g)))),
+ 	  gms %in% ggm,
+ 	  gms %in% tools:::get_S4_generics_with_methods(em), # with "message"
+ 	  ## all above worked in 2.7.0, however:
+ 	  isGeneric("show",  where=e4),
+ 	  hasMethods("show", where=e4), hasMethods("show", where=em),
630
+ 	  ## isGeneric("dim", where=as.environment("package:Matrix"))
631 632 633 634
+ 	  identical(as.character(gg4), #gg4 has packages attr.; tools::: doesn't
+ 		    tools:::get_S4_generics_with_methods(e4))
+ 	  )
> ## the last failed in R 2.7.0 : was not showing  "show"
635
> ## TODO: use "Matrix" checks once that is >= 1.0
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
> 
> ## containing "array" ("matrix", "ts", ..)
> t. <- ts(1:10, frequency = 4, start = c(1959, 2))
> setClass("Arr", contains= "array"); x <- new("Arr", cbind(17))
> setClass("Ts",  contains= "ts");   tt <- new("Ts", t.); t2 <- as(t., "Ts")
> setClass("ts2", representation(x = "Ts", y = "ts"))
> tt2 <- new("ts2", x=t2, y=t.)
> stopifnot(dim(x) == c(1,1), is(tt, "ts"), is(t2, "ts"),
+           ## FIXME:  identical(tt, t2)
+           length(tt) == length(t.),
+           identical(tt2@x, t2), identical(tt2@y, t.))
> ## new(..) failed in R 2.7.0
> 
> ## Method with wrong argument order :
> setGeneric("test1", function(x, printit = TRUE, name = "tmp")
+            standardGeneric("test1"))
[1] "test1"
653 654 655
> assertWarning_atleast(
+ setMethod("test1", "numeric", function(x, name, printit) match.call())
+ )## did not warn or error in R 2.7.0 and earlier
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
> 
> library(stats4)
> c1 <- getClass("mle", where = "stats4")
> c2 <- getClass("mle", where = "package:stats4")
> s1 <- getMethod("summary", "mle", where = "stats4")
> s2 <- getMethod("summary", "mle", where = "package:stats4")
> stopifnot(is(c1, "classRepresentation"),
+ 	  is(s1, "MethodDefinition"),
+ 	  identical(c1,c2), identical(s1,s2))
> ## failed at times in the past
> 
> ## Extending "matrix", the .Data slot etc:
> setClass("moo", representation("matrix"))
> m <- matrix(1:4, 2, dimnames= list(NULL, c("A","B")))
> nf <- new("moo", .Data = m)
> n2 <- new("moo", 3:1, 3,2)
> n3 <- new("moo", 1:6, ncol=2)
> stopifnot(identical(m,			as(nf, "matrix")),
+ 	  identical(matrix(3:1,3,2),	as(n2, "matrix")),
+ 	  identical(matrix(1:6,ncol=2), as(n3, "matrix")))
> ## partly failed at times in pre-2.8.0
> 
678 679 680
> ## From "Michael Lawrence" <....@fhcrc.org>  To r-devel@r-project, 25 Nov 2008:
> ## NB: setting a generic on order() is *not* the approved method
> ## -- set xtfrm() methods instead
681 682 683
> setGeneric("order", signature="...",
+ 	   function (..., na.last=TRUE, decreasing=FALSE)
+ 	   standardGeneric("order"))
684
Creating a new generic function for 'order' in the global environment
685 686 687 688
[1] "order"
> stopifnot(identical(rbind(1), matrix(1,1,1)))
> setGeneric("rbind", function(..., deparse.level=1)
+ 	   standardGeneric("rbind"), signature = "...")
689
Creating a new generic function for 'rbind' in the global environment
690 691 692 693
[1] "rbind"
> stopifnot(identical(rbind(1), matrix(1,1,1)))
> ## gave Error in .Method( .... in R 2.8.0
> 
694
> ## median( <simple S4> )
695 696 697 698 699 700 701 702 703 704 705 706 707
> ## FIXME: if we use "C" instead of "L", this fails because of caching
> setClass("L", contains = "list")
> ## {simplistic, just for the sake of testing here} :
> setMethod("Compare", signature(e1="L", e2="ANY"),
+           function(e1,e2) sapply(e1, .Generic, e2=e2))
[1] "Compare"
> ## note the next does *not* return an object of the class.
> setMethod("Summary", "L",
+ 	  function(x, ..., na.rm=FALSE) {x <- unlist(x); callNextMethod()})
[1] "Summary"
> setMethod("[", signature(x="L", i="ANY", j="missing",drop="missing"),
+           function(x,i,j,drop) new(class(x), x@.Data[i]))
[1] "["
708
> ## defining S4 methods for sort() has no effect on calls to
709
> ## sort() from functions in a namespace; e.g., median.default.
710 711 712 713 714
> ## but setting an xtfrm() method works.
> setMethod("xtfrm", "L", function(x) xtfrm(unlist(x@.Data)))
[1] "xtfrm"
> ## median is documented to use mean(), so we need an S3 mean method:
> ## An S4 method will not do because of the long-standing S4 scoping bug.
715 716 717 718 719 720
> mean.L <- function(x, ...) new("L", mean(unlist(x@.Data), ...))
> x <- new("L", 1:3); x2 <- x[-2]
> stopifnot(unlist(x2) == (1:3)[-2],
+ 	  is(mx <- median(x), "L"), mx == 2,
+ 	  ## median of two
+ 	  median(x2) == x[2])
721 722
> ## NB: quantile() is not said to work on such an object, and only does so
> ## for order statistics (so should not be tested, but was in earlier versions).
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
> 
> ## Buglet in as() generation for class without own slots
> setClass("SIG", contains="signature")
> stopifnot(packageSlot(class(S <- new("SIG"))) == ".GlobalEnv",
+ 	  packageSlot(class(ss <- new("signature"))) == "methods",
+ 	  packageSlot(class(as(S, "signature"))) == "methods")
> ## the 3rd did not have "methods"
> 
> ## Invalid "factor"s -- now "caught" by  validity check :
>  ok.f <- gl(3,5, labels = letters[1:3])
> bad.f <- structure(rep(1:3, each=5), levels=c("a","a","b"), class="factor")
> validObject(ok.f) ; assertError(validObject(bad.f))
[1] TRUE
> setClass("myF", contains = "factor")
> validObject(new("myF", ok.f))
[1] TRUE
> assertError(validObject(new("myF", bad.f)))
> removeClass("myF")
[1] TRUE
> ## no validity check in R <= 2.9.0
> 
> ## as(x, .)   when x is from an "unregistered" S3 class :
> as(structure(1:3, class = "foobar"), "vector")
[1] 1 2 3
> ## failed to work in R <= 2.9.0
> 
749 750 751 752 753 754 755 756 757 758 759
> ## S4 dispatch in the internal generic xtfrm (added in 2.11.0)
> setClass("numWithId", representation(id = "character"), contains = "numeric")
> x <- new("numWithId", 1:3, id = "An Example")
> xtfrm(x) # works as the base representation is numeric
[1] 1 2 3
attr(,"id")
[1] "An Example"
> setMethod('xtfrm', 'numWithId', function(x) x@.Data)
[1] "xtfrm"
> xtfrm(x)
[1] 1 2 3
760
> stopifnot(identical(xtfrm(x), 1:3))
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
> ## new in 2.11.0
> 
> ## [-dispatch using callNextMethod()
> setClass("C1", representation(a = "numeric"))
> setClass("C2", contains = "C1")
> setMethod("[", "C1", function(x,i,j,...,drop=TRUE)
+ 	  cat("drop in C1-[ :", drop, "\n"))
[1] "["
> setMethod("[", "C2", function(x,i,j,...,drop=TRUE) {
+     cat("drop in C2-[ :", drop, "\n")
+     callNextMethod()
+ })
[1] "["
> x <- new("C1"); y <- new("C2")
> x[1, drop=FALSE]
drop in C1-[ : FALSE 
NULL
> y[1, drop=FALSE]
drop in C2-[ : FALSE 
drop in C1-[ : FALSE 
NULL
> ## the last gave TRUE on C1-level in R 2.10.x;
> ## the value of drop was wrongly taken from the default.
> 
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
> ## All slot names -- but "class" -- should work now
> problNames <- c("names", "dimnames", "row.names",
+                 "class", "comment", "dim", "tsp")
> myTry <- function(expr, ...) tryCatch(expr, error = function(e) e)
> tstSlotname <- function(nm) {
+     r <- myTry(setClass("foo", representation =
+                         structure(list("character"), .Names = nm)))
+     if(is(r, "error")) return(r$message)
+     ## else
+     ch <- LETTERS[1:5]
+     ## instead of  new("foo", <...> = ch):
+     x <- myTry(do.call(new, structure(list("foo", ch), .Names=c("", nm))))
+     if(is(x, "error")) return(x$message)
+     y <- myTry(new("foo"));		 if(is(y, "error")) return(y$message)
+     r <- myTry(capture.output(show(x))); if(is(r, "error")) return(r$message)
+     r <- myTry(capture.output(show(y))); if(is(r, "error")) return(r$message)
+     ## else
+     slot(y, nm) <- slot(x, nm)
+     stopifnot(validObject(x), identical(x,y), identical(slot(x, nm), ch))
+     return(TRUE)
+ }
> R <- sapply(problNames, tstSlotname, simplify = FALSE)
> str(R) # just so ...
List of 7
 $ names    : logi TRUE
 $ dimnames : logi TRUE
 $ row.names: logi TRUE
 $ class    : chr "\"class\" is a reserved slot name and cannot be redefined"
 $ comment  : logi TRUE
 $ dim      : logi TRUE
 $ tsp      : logi TRUE
> stopifnot(is.character(R[["class"]]),
+           sapply(R[names(R) != "class"], isTRUE))
> ## only "class" (and ".Data", ...) is reserved as slot name
> 
> ## implicit generics ..
> setMethod("sample", "C2",
+           function(x, size, replace=FALSE, prob=NULL) {"sample.C2"})
823
Creating a generic function for 'sample' from package 'base' in the global environment
824 825 826 827 828 829 830 831 832 833 834 835 836
[1] "sample"
> stopifnot(is(sample,"standardGeneric"),
+ 	  ## the signature must come from the implicit generic:
+ 	  identical(sample@signature, c("x", "size")),
+ 	  identical(packageSlot(sample), "base"),
+ 	  ## default method must still work:
+ 	  identical({set.seed(3); sample(3)}, 1:3))
> ## failed in R 2.11.0
> 
> ## Still, signature is taken from "def"inition, if one is provided:
> ## (For test, qqplot must be a "simple" function:)
> stopifnot(is.function(qqplot) && identical(class(qqplot), "function"))
> setGeneric("qqplot", function(x, y, ...) standardGeneric("qqplot"))
837
Creating a new generic function for 'qqplot' in the global environment
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
[1] "qqplot"
> stopifnot(is(qqplot, "standardGeneric"),
+ 	  identical(qqplot@signature, c("x","y")))
> ## failed for a day ~ 2005-05-26, for R-devel only
> 
> 
> ##  'L$A@x <- ..'
> setClass("foo", representation(x = "numeric"))
> f <- new("foo", x = pi*1:2)
> L <- list()
> L$A <- f
> L$A@x[] <- 7
> if( identical(f, L$A) )
+     stop("Oops! f is identical to L$A, even though not touched!")
> ## did not duplicate in 2.0.0 <= Rversion <= 2.11.1
> 
854 855 856 857 858 859 860 861 862
> ## prototypes for virtual classes:  NULL if legal, otherwise 1st member
> ## OptionalPosixct above includes NULL
> stopifnot(is.null(getClass("OptionalPOSIXct")@prototype))
> ## "IntOrChar" had invalid NULL prototype < 2.15.0
> setClassUnion("IntOrChar", c("integer", "character"))
> stopifnot(is.integer(getClass("IntOrChar")@prototype))
> ## produced an error < 2.15.0
> stopifnot(identical(isGeneric("&&"), FALSE))
> 
863
>