Skip to content
Prev 31155 / 63421 Next

"for" loop wiht S4 Objects

On Fri, Jan 23, 2009 at 1:25 AM, Biczok Rudolf
<r.biczok at dkfz-heidelberg.de> wrote:
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