Effacer les filtres
Effacer les filtres

How to sort a table within groups

10 vues (au cours des 30 derniers jours)
Elbert Liu
Elbert Liu le 25 Juil 2019
Commenté : Ecco le 25 Jan 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.

Réponse acceptée

Adam Danz
Adam Danz le 25 Juil 2019
  1 commentaire
Elbert Liu
Elbert Liu le 25 Juil 2019
Thank you! It works!

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 25 Juil 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 commentaires
Yean Lim
Yean Lim le 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 le 25 Jan 2024
As I found the answer today and helpful:
There is a ",:" missing:
sortedtable = yourtable(ordering(:, 2),:);

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by