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

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Aug 15 23:18:15 CEST 2007

On Wed, 15 Aug 2007, Pijus Virketis wrote:

> I would like to get lapply() to work in the natural way on a class I've
> defined.

What you have not said is that this is an S4 class.

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

This works as documented for S3 methods (since as.list is S3 generic): it 
is a 'feature' of S4 methods that deserves to be much more widely 

> # dummy class
> setClass("test", representation(test="list"))
> # set up as.list()
> test.as.list <- function(x) x at test
> setMethod("as.list", signature(x="test"), test.as.list)
> # set up as.vector(x, mode="list")
> test.as.vector <- function(x, mode) x at test
> setMethod("as.vector", signature(x="test", mode="character"),
> test.as.vector)
> obj <- new("test", test=list(1, 2, 3))
> # this produces "Error in as.vector(x, "list") : cannot coerce to
> vector" on R 2.4.1
> lapply(obj, print)
> # these work
> lapply(as.list(obj), print)
> lapply(as.vector(obj, "list"), print)
> Thank you,
> Pijus

Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

More information about the R-help mailing list