How to use accumaray to aggregate text/string based?

8 vues (au cours des 30 derniers jours)
Bayu Ardiyanto
Bayu Ardiyanto le 8 Juin 2018
Commenté : Walter Roberson le 8 Juin 2018
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!

Réponses (1)

Razvan Carbunescu
Razvan Carbunescu le 8 Juin 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 commentaire
Walter Roberson
Walter Roberson le 8 Juin 2018
You could also look at categorical arrays.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Preprocessing dans Help Center et File Exchange

Produits


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by