Is it possible to add a new branch after the first fill?

Dear all,

i’ve a tree and i don’t know at first event all names of needed branches. It’s possible that at event N a new branch is needed.
Can i add it to the tree when needed and then fill it ?

I’ve tried with a simple code adding a vector and filling it.
Then on second event i add a new branch and fill it. Printing the tree i correctly find that second branch as only 1 entry while first one has 2. However drawing the second branch i find double entries than expected. Are them normalized to total tree entries ? Can i rescale them ?

Here is the code:

#include <vector>

void testTree()
{
  TTree *tree = new TTree("tree","tree");
  
  // event 1
  std::vector<float>* vecF1 = new std::vector<float>;
  tree->Branch("vecF1", &vecF1);
  vecF1->push_back(1.);
  vecF1->push_back(2.);
  tree->Fill();
  
  // event 2
  vecF1->clear();
  std::vector<float>* vecF2 = new std::vector<float>;
  tree->Branch("vecF2", &vecF2);
  vecF1->push_back(1.);
  vecF2->push_back(1.);
  tree->Fill();
  
  tree->Print();
  tree->Draw("vecF2");
}

Many thanks for any comment.

Regards,
Max

Hi,

In the general, we recommend that rather than adding branches you should create Friend. However it is possible to add a branch, the trick is to back fill the new branch without default value:[code]#include

void testTree()
{
TTree *tree = new TTree(“tree”,“tree”);

// event 1
std::vector* vecF1 = new std::vector;
tree->Branch(“vecF1”, &vecF1);
vecF1->push_back(1.);
vecF1->push_back(2.);
tree->Fill();

// event 2
vecF1->clear();
std::vector* vecF2 = new std::vector;
TBranch *b = tree->Branch(“vecF2”, &vecF2);
for (int i=0; i < tree->GetEntries; ++i) {
b->Fill();
}
vecF1->push_back(1.);
vecF2->push_back(1.);
tree->Fill();

tree->Print();
tree->Draw(“vecF2”);
} [/code]

Cheers,
Philippe.

Hi Philippe,

thanks it was indeed what i was looking for :slight_smile:

Cheers,
Max