# Merge horizontally TTrees with TBranch as key

**URL:** <https://root-forum.cern.ch/t/merge-horizontally-ttrees-with-tbranch-as-key/62279>\
**Category:** ROOT\
**Tags:** tree\
**Created:** [November 20, 2024, 9:49am UTC](https://root-forum.cern.ch/t/merge-horizontally-ttrees-with-tbranch-as-key/62279 "2024-11-20T09:49:10Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Danilo](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/danilo/32/34528_2.png) [@Danilo](https://root-forum.cern.ch/u/Danilo)\
**Post date:** [November 20, 2024, 1:15pm UTC](https://root-forum.cern.ch/t/merge-horizontally-ttrees-with-tbranch-as-key/62279/2 "2024-11-20T13:15:16Z")

</div>

Hi,

Thanks for the post, this is an interesting and not so easy problem, for which a standard and performant solution might not exist (and the reason is deeply rooted in the nature of the operation performed, not really in ROOT’s columnar IO).

Is `eventID` an integer value? In that case one could approach the problem [building an index](https://root.cern.ch/doc/master/classTTree.html#a3f6b5bb591ff7a5bd0b06eea6c12b998) based on that column to loop on identical events:

```auto
// Set up the 2 trees and the way to read them
tree1->BuildIndex("eventID");
tree2->BuildIndex("eventID");
for (auto id : eventIDCollection) {
   tree1->GetEntryWithIndex(id);
   tree2->GetEntryWithIndex(id);
   // Custom operations for the merging and writing the 3rd TTree
}

```

Alternatively, if everything fits in memory, you can resort to RDataFrame (see this post [Sort a RDataFrame](https://root-forum.cern.ch/t/sort-a-rdataframe/50739))

Cheers,  
Danilo

---

_[View the full topic](https://root-forum.cern.ch/t/merge-horizontally-ttrees-with-tbranch-as-key/62279)._
