フィルターのクリア

How to sort a table within groups

10 ビュー (過去 30 日間)
Elbert Liu
Elbert Liu 2019 年 7 月 25 日
コメント済み: Ecco 2024 年 1 月 25 日
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.

採用された回答

Adam Danz
Adam Danz 2019 年 7 月 25 日
  1 件のコメント
Elbert Liu
Elbert Liu 2019 年 7 月 25 日
Thank you! It works!

サインインしてコメントする。

その他の回答 (1 件)

Guillaume
Guillaume 2019 年 7 月 25 日
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 件のコメント
Yean Lim
Yean Lim 2020 年 11 月 3 日
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 2024 年 1 月 25 日
As I found the answer today and helpful:
There is a ",:" missing:
sortedtable = yourtable(ordering(:, 2),:);

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by