On Fri, Jan 23, 2009 at 1:25 AM, Biczok Rudolf <r.bic...@dkfz-heidelberg.de> wrote: > Hi all,
> I'm working with the S4-Class system and I have a little problem with > Implementing iteration functionality in my S4 class but it don't work: >> setClass("foo",representation(bar="list")) >> x <- new("foo",bar=list(1,2,3)) >>for(e in x) cat(e) > invalid type/length (S4/1) in vector allocation I'm not sure why you would expect a for loop to work there. Wouldn't a function in the "apply" family be more natural? At least in my code it is much more common to use lapply to loop over the elements of a list than it is to use 'for'. I once suggested to John Chambers that it would be a good idea to have a way of applying a function to the slots of an S4 object and he persuaded me otherwise. However, you can generate something like that with lapply(slotNames(x), function(nm) cat(slot(x, nm))) or create a list out of the S4 object S4toL <- function(x) {nms <- slotNames(x); names(nms) <- nms; lapply(nms, slot, object = x)} then use lapply on the result of S4toL > > > > > > But when I extend from a primitive vector it works: > > > >> setClass("foo",contains="list") > > > >> x <- new("foo",.Data=list(1,2,3)) > > > >>for(e in x) cat(e) > > 123 > > > > This is ok, but is there any other way to do this (for e.g. with a > generic function)? > > > > Thanks, > > Rudolf > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-devel@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-devel > ______________________________________________ R-devel@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-devel