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

Pijus Virketis pvirketis at hbk.com
Wed Aug 15 21:55:01 CEST 2007


I would like to get lapply() to work in the natural way on a class I've
defined. 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?

# 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"),

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,


More information about the R-help mailing list