How to use accumaray to aggregate text/string based?

8 visualizaciones (últimos 30 días)
Bayu Ardiyanto
Bayu Ardiyanto el 8 de Jun. de 2018
Comentada: Walter Roberson el 8 de Jun. de 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!

Respuestas (1)

Razvan Carbunescu
Razvan Carbunescu el 8 de Jun. de 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

Categorías

Más información sobre Data Preprocessing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by