Clear Filters
Clear Filters

How to sort a table within groups

10 views (last 30 days)
Elbert Liu
Elbert Liu on 25 Jul 2019
Commented: Ecco on 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.

Accepted Answer

Adam Danz
Adam Danz on 25 Jul 2019

More Answers (1)

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

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!