[R] getting lapply() to work for a new class

Martin Morgan mtmorgan at fhcrc.org
Thu Aug 16 00:30:50 CEST 2007


Pijus,

My 2 cents, which might be post-hoc rationalization.

If your class 'is' a list, with additional information, then

setClass("Test", contains="list")

and you're ready to go.

On the other hand, if your class 'has' a list, along with other
information, create an accessor

setGeneric("test", function(object) standardGeneric("test"))
setMethod("test",
          signature=signature(object="Test"),
          function(object) slot(object, "test"))

obj <- new("Test", test=list(1,2,3))
lapply(test(obj), print)

(You could define a generic on 'lapply' and a method that dispatches
to your class, but that implies that Test 'is' a list).

Martin


"Pijus Virketis" <pvirketis at hbk.com> writes:

> Thank you.
>
> When I tried to set as.list() in baseenv(), I learned that its bindings
> are locked. Does this mean that the thing to do is just to write my own
> "lapply", which does the coercion using my "private" as.list(), and then
> invokes the base lapply()?
>
> -P
>
> -----Original Message-----
> From: Prof Brian Ripley [mailto:ripley at stats.ox.ac.uk] 
> Sent: Wednesday, August 15, 2007 5:18 PM
>
>> As far as I can tell, lapply() needs the class to be coercible to a 
>> list. Even after I define as.list() and as.vector(x, mode="list") 
>> methods, though, I still get an "Error in as.vector(x, "list") : 
>> cannot coerce to vector". What am I doing wrong?
>
> Not considering namespaces.  Setting an S4 method for as.list() creates
> an object called as.list in your workspace, but the lapply function uses
> the as.list in the base namespace.  That's the whole point of
> namespaces: to protect code against redefining functions.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Martin Morgan
Bioconductor / Computational Biology
http://bioconductor.org



More information about the R-help mailing list