Filter löschen
Filter löschen

How to sort a table within groups

10 Ansichten (letzte 30 Tage)
Elbert Liu
Elbert Liu am 25 Jul. 2019
Kommentiert: Ecco am 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.

Akzeptierte Antwort

Adam Danz
Adam Danz am 25 Jul. 2019

Weitere Antworten (1)

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by