Adding two histograms from two different root directories

Hi,
I have a root file with two directories, say, dir1 and dir2. The two directories contain two different histograms, hist1 and hist2. I need to add these two histograms. Can anybody please tell me how can I do it from the root prompt with a command line?

Thank you.

Hi @Sbecka,
you can retrieve a histogram from a directory with

root [0] auto f = TFile::Open("yourfile.root");
root [1] auto h = f->Get<TH1>("dir1/histogramname")

and when you get the two histograms you can add one to the other with h1->Add(h2).

Hope this helps!
Enrico

Thanks Enrico.

When I add two histograms from the same directory using Add method, it works fine. But when I follow the procedure you described and try to add two histograms afterwards, it shows me error message ,
ROOT_prompt_3:1:5: error: no member named ‘Add’ in ‘TObject’.
Do you have any insight why this can happen?

Ah sorry, the plain f->Get returns a TObject* (that you can cast to a TH1*). With a recent enough ROOT version you can instead call f->Get<TH1>("...") to directly retrieve a pointer of the desired type, otherwise you can do something like static_cast<TH1*>(f->Get("...")) – edited the original code snippet now.

Cheers,
Enrico

Now it works, thank you so much!

1 Like