Merging trees in root

Hi, I am trying to Merge 2 or 3 LHEF trees using root. My final TTree has the correct structure, but the values are not saved. The relavant code is the following. The Init function just sets the branch adresses of the initial trees:

TFile* fFile = (TFile*)TFile::Open(filename.Data());
  TTree* tree1 = (TTree*)fFile->Get("LHEF");

  TFile* fFile2 = TFile::Open(filename2.Data());
  TTree* tree2 = (TTree*)fFile2->Get("LHEF");

  TFile* fFile3 = TFile::Open(filename3.Data());
  TTree* tree3 = (TTree*)fFile3->Get("LHEF");

  TFile *outfile = new TFile(outfilename, "RECREATE");
  TTree *mergedTree = new TTree("mergedTree", "Merged Tree");

  mergedTree->Branch("Event", &Event_, "fUniqueID/I:fBits/I:Number/I:Nparticles/I:ProcessID/I:Weight/F:ScalePDF/F:CouplingQED/F:CouplingQCD/F");
  mergedTree->Branch("Rwgt", &Rwgt_, "fUniqueID/I:fBits/I:Weight/F");
  mergedTree->Branch("Particle", &Particle_, "fUniqueID/I:Particle.fBits/I:Particle.PID/I:Particle.Status/I:Particle.Mother1/I:Particle.Mother2/I:Particle.ColorLine1/I:Particle.ColorLine2/I:Particle.Px/F:Particle.Py/F:Particle.Pz/F:Particle.E/F:Particle.M/F:Particle.PT/F:Particle.Eta/F:Particle.Phi/F:Particle.Rapidity/F:Particle.LifeTime/F:Particle.Spin/F");

  int nentries1 = tree1->GetEntries();
  for (int i = 0; i < nentries1; i++) {

  int nentries2 = tree2->GetEntries();
  cout << "TEST" << Particle_PT[5] << endl;
  for (int i = 0; i < nentries2; i++) {


  int nentries3 = tree3->GetEntries();
  for (int i = 0; i < nentries3; i++) {

  // Save the merged tree to a file

  cout << "<I> Merged tree saved to file: " << outfilename << endl;

I would appreciate any help, if someone knows why the values of the initial trees aren’t stored in the merged one. Thank you.

  • Jonathan

hadd -?

Hi, when using hadd, the trees merge end to end. I.e. the total number of events goes to 30000, with 10000 events from each tree. I need the branches from the three trees to be merges to a single branch on the final tree, i.e. all pt values from all trees on the same final branch, such that the final number of events is the same as in the input trees…

ROOT offers the concept of friends for TTree / TChain (see TTree::AddFriend / TChain::AddFriend).
See also, e.g.: ${ROOTSYS}/tutorials/tree/treefriend.C

If you attach your files, we could try to create a “monolithic” tree.