Sort table based on number of occurrences

3 ビュー (過去 30 日間)
Marcus Glover
Marcus Glover 2021 年 9 月 6 日
コメント済み: Marcus Glover 2022 年 10 月 29 日
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.

採用された回答

Peter Perkins
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 件のコメント
Marcus Glover
Marcus Glover 2022 年 9 月 20 日
編集済み: Marcus Glover 2022 年 9 月 20 日
Sorry to dig this up- the table creadted from my SQL pull has either 'cell' or 'double' as the datatypes. Is there a way to batch convert only the 'cell' types to 'categorical'?
Would there be a reason not to do this? Some of the cells do contain numbers- but those are for identification purposes (like a serial number) and will never be used as 'numbers'.
Thanks.
Marcus Glover
Marcus Glover 2022 年 10 月 29 日
I fihured this out...
T=convertvars(T,@iscell,'categorical');

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeTables についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by