yuk
yuk

Reputation: 19870

Is there lapply-like function for S4 object?

To apply a function to all slots in S4.

Of course, it can be done with for-loop over slotNames(). But I'm curious if it can be done in a vectorized way.

Upvotes: 1

Views: 621

Answers (1)

JDL
JDL

Reputation: 1654

In general it isn't possible to operate on slots in a vectorised way, because the slots might have any class. If a class has structure

slotA = "factor"
slotB = "integer"
slotC = "numeric"

then even though you might be applying the same (generic) function to all of them (say, summary) the actual methods that get called will be different. The task just isn't vectorisable, any more than the set of commands "mop the floor, wash the car and vacuum the carpet" could be vectorised even though they might all share the generic function clean — you need a mop for one task, a sponge for another and a vacuum cleaner for the third. (Contrast that with the set of commands "vacuum the three carpets in the bedroom, hallway and lounge" which can be vectorised to an extent — you don't have to get the vacuum cleaner out of the box three times and put it away three times, you can do it just once)

If you can guarantee that all the slots will be of the same class, then it becomes easier to vectorise, but if that is the case, why does this object have the structure that it does? If it needs to be S4 then just define a simple class that contains a list, matrix or array and then use sapply or apply as needed.

Upvotes: 2

Related Questions