Merging TTrees on the fly

Hi All,

i know how to merge TTrees which are stored in a TFile, i.a. with the
chain.Add - Method
But this doesn’t work for TTrees which have not been written yet to a TFile: for example, i read out a TTree T1 from a TFile, generated two other Trees T2, T3 within my macro. T2 and T3 dont’t exist in a TFile yet.
So i whant to merge T1, T2 and T3 and after that, to write the merged Tree in a new TFile.
I made several attempts with ‘Add’ or ‘AddFriend’ but no success !
Please can anybody give me some hints how to do that ?

Thank You !

TTree::Add does not exist!
To merge Trees, use the static function TTree::MergeTrees, eg

  TTree *tree1, *tree2, *tree3; //pointers to your 3 Trees
  TList *list = new TList;
  list->Add(tree1);
  list->Add(tree2);
  list->Add(tree3);
  TTree *newtree = TTree::MergeTrees(list);
  newtree->SetName("newtree");
  newtree->Write();

Rene

Thank You Rene, i guess this was a typical newbee question ( because if i
would have looked more closely in the reference guide i would have found out myself, sometime…).
So concerning ‘merging trees’ there is one thing i honestely didn’t figure yet :

  TFile *ft = new TFile("tfile.root","UPDATE");
     
  t1 = (TTree *)ft->Get("T");
  
  TTree *t2 = new TTree("T","Title");
  
  // create something to fill with here //

  t2->Fill();
      
  TList *list = new TList; 
  list->Add(t1); 
  list->Add(t2); 
  
  TTree *newtree = TTree::MergeTrees(list); 
  newtree->SetName("T"); 
  newtree->Write();
        
  ft->Close();

So my problem is, i want to run that procedure several times.
BUT in every procedure the tfile.root is updated in this sense, that
each time a tree ‘T’ is created so that the tfile.root finally contains something like T;1 T;2 T;3 and so on.
Is there any way to avoid the “numbering” of the trees in the TFile so that the final TFile only contains ONE tree named T ?

Thanks ,Axel

Hi Axel,
see TObject::Write, kWriteDelete.
Axel.

Thank You Axel.

Ahh… well after the fifth day of using ROOT i slightly become used to it ( and to it’s reference guide as well…). I looks like a very powerfull tool and the forum is a good place to stay too :slight_smile:

greetings, Axel