# Sort RDataFrame

**URL:** <https://root-forum.cern.ch/t/sort-rdataframe/43170>\
**Category:** ROOT\
**Tags:** rdataframe\
**Created:** [January 19, 2021, 9:40pm UTC](https://root-forum.cern.ch/t/sort-rdataframe/43170 "2021-01-19T21:40:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ecatanzani](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/ecatanzani/32/24189_2.png) [@ecatanzani](https://root-forum.cern.ch/u/ecatanzani)\
**Post date:** [January 19, 2021, 9:40pm UTC](https://root-forum.cern.ch/t/sort-rdataframe/43170/1 "2021-01-19T21:40:40Z")

</div>

Dear ROOT experts,  
I have a ROOT DataFrame containing events each one tagged with a certain energy value.  
Is it possible to select the N events with the highest energy value ?

A similar topic can be found here: [Sorting a DataFrame](https://root-forum.cern.ch/t/sorting-a-dataframe/31426/3)  
Is possible to use something similar for this case ?

Thanks  
Enrico

* * *

\_ROOT Version 6.22  
\_Platform: Linux (CentOS 7)  
\_Compiler: gcc 7 via DevToolSet 7

* * *

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [January 20, 2021, 8:28am UTC](https://root-forum.cern.ch/t/sort-rdataframe/43170/2 "2021-01-20T08:28:17Z")

</div>

Hi Enrico,  
depending on the size and complexity of the dataset, you can:

- use `Take` to extract vectors with all entries, then get the indices of the N events with the highest energy values and inject those into a new RDF that writes them out
- [book a custom action](https://root.cern/doc/master/classROOT_1_1RDF_1_1RInterface.html#a9ed8313806398d106bfc2390301c0408) that implements a “max N elements” operation
- use a `Foreach` that keeps an updated list of the contents of the N events with highest energy

In any case you will need to do one pass over the dataset to extract these N events and then another pass over the N events to write them out. To write the entries of a vector using RDF you can use something like:

```c++
std::vector<double> my_energies;
ROOT::RDataFrame(my_energies.size())
   .Define("energy", [&](ULong64_t entry) { return my_energies[entry]; }, {"rdfentry_"})
   .Snapshot("t", "f.root", {"energy"});

```

Cheers,  
Enrico

---

<div class="post-metadata">

**Author:** ![system](https://root-forum.cern.ch/uploads/default/original/3X/e/f/efe4f24398fd8ffeb76bccb6ecc46d9d9c003376.png) [@system](https://root-forum.cern.ch/u/system)\
**Post date:** [February 3, 2021, 8:28am UTC](https://root-forum.cern.ch/t/sort-rdataframe/43170/3 "2021-02-03T08:28:28Z")

</div>

Closed on February 3, 2021, 8:28am UTC

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