[R] "[[<-","[[" default?
Henrik Bengtsson
hb at maths.lth.se
Thu Oct 2 14:35:30 CEST 2003
It depends, but a quick answer is that you in general should use
NextMethod() as far as possible to avoid ad hoc solutions and tricky
side effects. Example:
x <- list(a=1:10, b=base::letters);
class(x) <- "ClassA";
"[[.ClassA" <- function(object, name) {
# Here you are allowed to do something, cf. UseMethod().
name <- tolower(name); # e.g. make x[["A"]] equal to x[["a"]].
NextMethod("[[");
}
If ClassA inherits from ClassB and there is a function "[[.ClassB"()
defined, then this will of course *not* call "[[.default"(), but
"[[.ClassB"(). However, this what you should expect from a good
object-oriented design!
Maybe the above answers your question. If not, continue to read.
I can't recall the example, but I have indeed seen a case where we
wanted to called the default method explicitly. To do this, the only
thing you can do is unfortunately to unclass() your object and this
could have side effects that you do not want:
"[[.ClassA" <- function(object, name) {
# Here you are allowed to do something, cf. UseMethod().
name <- tolower(name); # e.g. make x[["A"]] equal to x[["a"]].
unclass(object)[[name]];
}
unclass() should normally be avoided since it is a nasty workaround.
Probably not in this case with "[[", but with other generic functions,
it can happen that default method in turn calls other generic functions.
Since you have unclassed the object the wrong method will be called by
those downstream generic functions.
My conclusion is that, and maybe this is what you are fishing for, there
should really exist a generic function and a separate default function
for "[[". What do the R-developers think?
The following will of course not work (it will generate an infinite
recursive call):
"[[.ClassA" <- function(object, name) {
# Here you are allowed to do something, cf. UseMethod().
name <- tolower(name); # e.g. make x[["A"]] equal to x[["a"]].
fcn <- .Primitive("[[");
# or fcn <- get("[[", mode="function");
fcn(object, name);
}
Henrik Bengtsson
Lund University
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Wolski
> Sent: den 2 oktober 2003 13:30
> To: r-help at stat.math.ethz.ch
> Subject: [R] "[[<-","[[" default?
>
>
> Hi!
>
> I have implemented class specific behaviour of
> "[[<-.myclass"<-function(). How it is posible to call the
> "[[.default" on an object of myclass?
>
> Eryk
>
> Dipl. bio-chem. Eryk Witold Wolski @ MPI-MG Dep.
> Vertebrate Genomics
> Ihnestrasse 73 14195 Berlin 'v'
> tel: 0049-30-84131285 / \
> mail: wolski at molgen.mpg.de ---W-W----
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo> /r-help
More information about the R-help
mailing list