1

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.

yuk
  • 19,098
  • 13
  • 68
  • 99
  • That seems like such an unusual operation I doubt there is a built in function for that. Seems like you could probably easily write your own wrapper in like 3 lines though. There's no reason to fear your own code. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick May 17 '19 at 17:05
  • 1
    This looks like a duplicate of this question: https://stackoverflow.com/questions/51110439/looping-through-variables-in-dynamically-created-s4-class-in-r/51174014 – JDL May 20 '19 at 07:41

1 Answers1

2

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.

JDL
  • 1,496
  • 10
  • 18