Thank you for your response. What you have suggested seems to be very simple.
In the meantime, I have succeeded in writing a macro using TSelector Class. It works fine. But crashes while processing it with PROOF. You can find details of this issue here:
PROOF Crashes while Writing Histogram