Sort table based on number of occurrences
3 ビュー (過去 30 日間)
古いコメントを表示
I have a table that I'd like to sort based on groups of a few of the columns. My table is made up of cells.
>> T=table({'A','B','C','B','B'}',{1,2,3,4,5}',{'Car','Van','Car','Car','Car'}')
T =
5×3 table
Var1 Var2 Var3
_____ _____ _______
{'A'} {[1]} {'Car'}
{'B'} {[2]} {'Van'}
{'C'} {[3]} {'Car'}
{'B'} {[4]} {'Car'}
{'B'} {[5]} {'Car'}
I'd like to sort by the number of occurences of Var1 and Var3, starting with the Var1- so since 'B' occurs 3 times, and 'Car' occurs twice with 'B', then the solution would be:
Var1 Var2 Var3
_____ _____ _______
{'B'} {[4]} {'Car'}
{'B'} {[5]} {'Car'}
{'B'} {[2]} {'Van'}
{'A'} {[1]} {'Car'}
{'C'} {[3]} {'Car'}
Is there someting like accumarray for strings? I tried groupsummary, but it will combine rows- Var2 is not always unique.
0 件のコメント
採用された回答
Peter Perkins
2022 年 3 月 2 日
This has been unanswered for some time. Maybe this is still helpful.
The main problem here is cell arrays of (repeated) text and numeric. Don't use those unless you have to, and you probably don't.
>> T = table(categorical({'A','B','C','B','B'}'), ...
[1,2,3,4,5]', ...
categorical({'Car','Van','Car','Car','Car'}'));
>> cats1 = categories(T.Var1);
>> [~,order1] = sort(countcats(T.Var1),'descend');
>> T.Var1 = reordercats(T.Var1,cats1(order1));
>> cats3 = categories(T.Var3);
>> [~,order3] = sort(countcats(T.Var3),'descend');
>> T.Var3 = reordercats(T.Var3,cats3(order3));
>> sortrows(T,["Var1" "Var3"])
ans =
5×3 table
Var1 Var2 Var3
____ ____ ____
B 4 Car
B 5 Car
B 2 Van
A 1 Car
C 3 Car
3 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Tables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!