Sort table based on number of occurrences
2 次查看(过去 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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!