Modifying TTree

I see this question asked a lot, and it is never properly answered. I want to modify a TTree, for example multiply square all the entries. To do this with a normal container, I would iterate through it and modify the entries. Apparently this is impossible, so instead I would like to dump the contents of the TTree into a text file, modify it, and make a new tree. Is this possible?

I don’t know if it’s possible to modify a TTree in place as you would modify a container (the TTree is stored on disk and the container would be in memory, so it’s not exactly the same thing), but certainly there are ways to read a TTree, square the values of a branch and write the new branch in a new TTree.

This is how you do it with TDataFrame (requires at least ROOT v6.10):

#include "ROOT/TDataFrame.hxx"
using ROOT::Experimental;

int main() {
  TDataFrame d("tree", "inputfile.root");
  // `define` a new branch "xsquared", `snapshot` all the data to a new file
  d.Define("xsquared", "x*x").Snapshot("tree", "outputfile.root");
  return 0;

outputfile.root will have all the branches of the tree in inputfile.root plus a new branch xsquared with the squares of branch x. (I have not tested the code but I did stare at it for a bit and I think it should do the job).
More information on TDataFrame can be found here.
Of course there are many other ways to read data in and write data out, the forum and ROOT’s tutorials are full of examples.

Hope this helps.

1 Like

Hi Enrico,

Thank you for your reply. This isn’t really what I want to do. What I am looking for is to convert the TTree a text table. Something like TTree::Scan(), except I want the data available in the program instead of sent to sto. Is that possible?


yes I read your question, but dumping a tree to a text file, modify entries and then make a new tree from the text file is inefficient and prone to errors so I thought I’d suggest an alternative approach :slight_smile:

Anyway: just read the entries to have them available in your program, here is a list of the different methods to read values from a TTree with links to tutorials.

For example, with TTreeReader:

void read() {
  TFile f("file.root"); // open file
  TTreeReader r("tree", &f); // create reader for tree "tree" in file f
  TTreeReaderValue<double> x(r, "x"); // attach object `x` to branch "x"
    std::cout << *x << std::endl;

and with TDataFrame:

void PrintValue(double x) { std::cout << x << std::endl; }

void read() {
  ROOT::Experimental::TDataFrame d("tree", "file.root");
  // for each entry, call `printValue` on branch "x"
  d.Foreach(PrintValue, {"x"}); 
1 Like

Hi Enrico,

Thank you very much, I think this may work for what I need to do.


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