How to use accumaray to aggregate text/string based?
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi!
I know that we can use accumaray for aggregating some value based on key variable, but can we use it to aggregate string as well? My code to aggregate number value:
a=[11;22;22;11;22;11];
b=[10;20;30;10;20;60];
c=['a';'c';'b';'a';'b';'d'];
[i, ~,n]=unique(a,'first'); %find unique
Mode = accumarray(n , b , size(i) , @(x) mode(x)); %find mode based on keys a
This will resulting Mode=[10;20]
For example, I want to use "Mode" for text based variable, i.e. resulting Text=[a,b]
Is it possible to do it? Any help will be appreciated.
Regards!
0 Kommentare
Antworten (1)
Razvan Carbunescu
am 8 Jun. 2018
accumarray is for numerics only but if c is going to only be single characters then can probably still use accumarray as chars are treated as numerics for most functions.
>> a=[11;22;22;11;22;11]';
>> b=[10;20;30;10;20;60]';
>> c=['a';'c';'b';'a';'b';'d']';
>> [i, ~,n]=unique(a,'first'); %find unique
>> res = accumarray(n , c ,size(i), @mode)
res =
2×1 char array
'a'
'b'
If you want to do grouping for more general text can look at groupsummary or findgroups / splitapply workflow to use with char vectors or strings.
>> t = table(a,b,c);
>> groupsummary(t,'a','mode',{'b' 'c'})
ans =
2×4 table
a GroupCount mode_b mode_c
__ __________ ______ ______
11 3 10 a
22 3 20 b
1 Kommentar
Siehe auch
Kategorien
Mehr zu Data Preprocessing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!