Azzera filtri
Azzera filtri

How to sort a table within groups

10 visualizzazioni (ultimi 30 giorni)
Elbert Liu
Elbert Liu il 25 Lug 2019
Commentato: Ecco il 25 Gen 2024
Hi all,
I have a table with variables 'Date', 'ID', Price', 'Volumn', all with daily value. The 'Date' repeats itself. Now I want to first group the table based on 'Date', and within each group (namely each date), I want to sort the table according to 'Price', from high to low. I know varfun can help me gruop the table and do the sorting, but the output will not contain 'ID' and 'Volumn'. I still want to researve the other variables. What shall I do?
Many thanks.

Risposta accettata

Adam Danz
Adam Danz il 25 Lug 2019

Più risposte (1)

Guillaume
Guillaume il 25 Lug 2019
I don't think you can use varfun for this. This is how I'd do it:
group = findgroups(yourtable.Date);
ordering = cell2mat(splitapply(@(x) {sortrows(x)}, [yourtable.Price, (1:height(yourtable))'], group));
sortedtable = yourtable(ordering(:, 2));
The trick here is to sort by price in each group but keep track of the original row (ordering(:, 2)) from the whole table, then reorder according to that.
  2 Commenti
Yean Lim
Yean Lim il 3 Nov 2020
Hi, I tried to run
sortedtable = yourtable(ordering(:, 2));
However, I got an error message saying:
Subscripting into a table using one subscript (as in t(i)) or three or more subscripts (as in t(i,j,k)) is not
supported. Always specify a row subscript and a variable subscript, as in t(rows,vars).
Please advise how to fix this error. Thanks
Ecco
Ecco il 25 Gen 2024
As I found the answer today and helpful:
There is a ",:" missing:
sortedtable = yourtable(ordering(:, 2),:);

Accedi per commentare.

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by