I have root file with directory called “bin4mu” and this directory containg a lot of histograms “TH1D”.
I need to rebin all the histograms in the old root file and write them to a new root file under directory called “bin4mu”.
I added the check you mentioned and it is partially working.
Even all the histograms in the input root file are TH1D, the loop don’t pass this continue statement if (!h) continue;
I attached the input root file.
There are some histograms with zero entries but I don’t think this is the problem.
It is strange, because for me the loop stops at step3 in the cout statements and I have an empty output root file.
Let me post again here my macro may be I didn’t get something you already mentioned.
TFile* outfile = TFile::Open("shapeBDTG_4mu_rebinned.root", "RECREATE");
TFile* infile = TFile::Open("shapeBDTG_4mu.root", "READ");
TKey* key;
TIter nextkey(gDirectory->GetListOfKeys());
while ((key = static_cast<TKey*>(nextkey())))
{
TObject* obj = key->ReadObj();
std::string name = obj->GetName();
if ( obj->IsA()->InheritsFrom("TDirectory") && name == "bin4mu") // loop over TDirectory derivatives
{
printf("Found a TDirectory (or its derivative) with a name \"%s\"...\n", name.c_str());
outfile->mkdir(name.c_str());
infile->cd(obj->GetName());
TIter nextkey1(gDirectory->GetListOfKeys());
TKey* key1;
while ((key1 = static_cast<TKey*>(nextkey1()))) // loop over objects in that TDirectory derivative
{
TObject* obj1 = key1->ReadObj();
if (obj1->IsA()->InheritsFrom("TH1") && !obj1->IsA()->InheritsFrom("TH2")) // only 1D histograms
{
TH1* h = static_cast<TH1*>(obj1);
if (h)
{
printf("\tFound a TH1 (or its derivative) with a name \"%s\", rebinning...\n", h->GetName());
h->Rebin(2);
outfile->cd(name.c_str());
h->Write();
}
}
}
}
}
outfile->Write();
outfile->Close(); infile->Close();