How to attribute a letter to unique combinaisons

1 回表示 (過去 30 日間)
012786534
012786534 2020 年 9 月 17 日
コメント済み: 012786534 2020 年 9 月 17 日
Hi,
I have a very simple question that is a bit tricky to explain: I have a table like this
var_a = {'T1','T1','T1','T1','T1','T1','T2','T2','T2','T2','T2','T2','T2','T2'}';
var_b = [2,2,2,2,3,3,8,8,8,9,9,10,10,11]';
t = table(var_a, var_b)
and for every unique var_a id, I want every unique combinaison between var_a and var_b to be attributed a different letter beginning with 'A'. In other words the desired output would looks like this:
var_a = {'T1','T1','T1','T1','T1','T1','T2','T2','T2','T2','T2','T2','T2','T2'}';
var_b = [2,2,2,2,3,3,8,8,8,9,9,10,10,11]';
var_c = {'A', 'A', 'A', 'A', 'B', 'B', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'D'}';
desired_out_put = table(var_a, var_b, var_c)
Thank you,

採用された回答

Stephen23
Stephen23 2020 年 9 月 17 日
編集済み: Stephen23 2020 年 9 月 17 日
There does not seem to be a convenient way to apply a function to table groups that does not also accumulate the results (e.g. like splitapply does). Here is one workaround:
>> A = {'T1';'T1';'T1';'T1';'T1';'T1';'T2';'T2';'T2';'T2';'T2';'T2';'T2';'T2'};
>> B = [2;2;2;2;3;3;8;8;8;9;9;10;10;11];
>> T = table(A,B)
T =
A B
____ __
'T1' 2
'T1' 2
'T1' 2
'T1' 2
'T1' 3
'T1' 3
'T2' 8
'T2' 8
'T2' 8
'T2' 9
'T2' 9
'T2' 10
'T2' 10
'T2' 11
>> G = findgroups(T.A);
>> F = @(b) {num2cell(char('A'+cumsum([0;diff(b)~=0])))};
>> Y = splitapply(F,T.B,G);
>> T.C = cell(height(T),1); % preallocate
>> for k = 1:max(G), T{G==k,'C'} = Y{k}; end
>> T
T =
A B C
____ __ ___
'T1' 2 'A'
'T1' 2 'A'
'T1' 2 'A'
'T1' 2 'A'
'T1' 3 'B'
'T1' 3 'B'
'T2' 8 'A'
'T2' 8 'A'
'T2' 8 'A'
'T2' 9 'B'
'T2' 9 'B'
'T2' 10 'C'
'T2' 10 'C'
'T2' 11 'D'
  1 件のコメント
012786534
012786534 2020 年 9 月 17 日
Neat answer. Thank you.

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by