Producing a TTree with some special branches of other TTrees

I have several trees with the same entries. And I want to create another tree with the some selected branches of these old trees.
Something like this-

Is there any efficient way to do it?

Thanks :wink:

yes, TTree allows you to do pretty much all sorts of tree transformations.

Assuming your branches contain doubles (haven’t tested the code, but it should give you an idea):

#include <TTree.h>
#include <TFile.h>

int main()
  // get tree1
  TFile f1("tree1.root");
  TTree *t1 = nullptr;
  f1.GetObject("tree1", t1);

  // get tree2
  TFile f2("tree2.root");
  TTree *t2 = nullptr;
  f1.GetObject("tree2", t2);

  // link variables b1, b2 to branches B1, B2
  double b1, b2;
  t1->SetBranchAddress("B1", &b1);
  t2->SetBranchAddress("B2", &b2);

  // create output tree
  TFile out_file("output.root", "recreate");
  TTree out_t("out_tree", "out_tree");

  // create output branches B1, B2, linked to variables b1, b2
  out_t.Branch("B1", &b1);
  out_t.Branch("B2", &b2);

  // for each entry, read b1, b2 from t1, t2, write them to out_t
  const ULong64_t nEntries = t1->GetEntries();
  for (ULong64_t e = 0; e < nEntries; ++e) {

  return 0;

Hope this helps!

1 Like

Hello Enrico,
Thanks a lot! It is working :tada::confetti_ball:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.