Retrieving variables from Tree

Hi everyone,
I have a beginner’s question.

I am trying too manipulate a RooRealVar, and I read somewhere in the forum that the only way to do that is to manipulate variables directly from the tree. So I’m trying to add a new branch with the log of a variable, but I’m struggling to do that.
I know in python I can just do (assuming tree has a branch named x)

for event in tree:
    logx = log10(event.x)

What is the equivalent in C++?



Here’s an example of how to read data from a tree in C++:

As for adding new branches to a TTree, you can find documentation in the TTree class:

Hope that helps!


Hi @etejedor, thanks for your answer.
I can’t make it work though. My code is

TFile *file = new TFile("../All_tmp.root");
TTree *tree = (TTree*)file->Get("Xib0/mytree");
TTreeReader reader ("Xib0/mytree",file);
TTreeReaderValue<Float_t> ipchi2 (reader,"lab0_IPCHI2_OWNPV");
Float_t loglab0;
TBranch* newbranch = tree->Branch("loglab0IPCHI2",&loglab0,"loglab0IPCHI2/F");
while (reader.Next()){
    loglab0 = log10(*ipchi2);
RooRealVar y("loglab0IPCHI2","loglab0IPCHI2",-2.5,6.);

and it doesn’t correctly load variable y when I try to sPlot it (see images 2 and 3 below).
Maybe you see what’s wrong?mysPlot.pdf (34.5 KB)

@StephanH can a branch that has been just written be used by RooRealVar here?

Also, I have doubts if it is possible to both read and write the same TTree simultaneously, or if you need to read one tree and write in another, then close the file of the latter. @pcanal can perhaps comment.

Thanks @etejedor. Let’s wait for the experts response!

When done carefully and in different branches, you should be able to read and write to the same TTree. The code snippet does not indicate how the RooRealVar is attached to the existing TTree. For example it might be opening a 2nd copy of the file in which case ordering of things might matter a lot; In this regard, in the above snippet the file should probably be opened in Update mode and the TFile and/or TTree written.

Thanks for the suggestion @pcanal. I’ll try to get things working.