How to attribute a letter to unique combinaisons
조회 수: 1 (최근 30일)
이전 댓글 표시
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,
댓글 수: 0
채택된 답변
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'
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!