Table row retrieval with dependent on column values
18 次查看(过去 30 天)
显示 更早的评论
I am dealing with a sorting issue on a table which. The table looks like follows:
Rec_id =[1; 1; 2; 2; 2; 3; 3; 4; 4]; % for clarification: the values here go up to 80 in the original table
Rec_type= {'A';'B';'A';'B';'C';'A';'C';'A';'B'};
data_table = table(Rec_id, Rec_type)
From this I'm trying to extract all rows of Rec_id's which have Rec_type='B', but also the rows of the same Rec_id with Rec_type='A'.
The table i try to extract from the former should look like this:
Rec_id =[1; 1; 2; 2; 4; 4]; % Rec_id = 3 gets filtered out completely, since there is no Rec_id = 3 with Rec_type 'B'
Rec_type= {'A';'B';'A';'B';'A';'B'};
new_table = table(Rec_id, Rec_type)
My approach was to find all Rec_id's that have a Rec_type of 'B' and use these.
Ids_corr_to_type_B = table.Rec_id(table.Rec_type == 'B');
But I was unable to use the array retrieved from that operation successfully.
Thank you for your help!
0 个评论
采纳的回答
Dyuman Joshi
2023-11-16
Rec_id =[1; 1; 2; 2; 2; 3; 3; 4; 4]; % for clarification: the values here go up to 80 in the original table
Rec_type= {'A';'B';'A';'B';'C';'A';'C';'A';'B'};
data_table = table(Rec_id, Rec_type);
%Row indices which have Rec_type as {'B'}
idx1 = contains(data_table.Rec_type, 'B')
%Get the corresponding Rec_ids
arr1 = data_table.Rec_id(idx1)
%Row indices which contain Rec_type as {'A'} and have the same Rec_id as {'B'}
idx2 = contains(data_table.Rec_type, 'A') & ismember(data_table.Rec_id, arr1)
%Output
new_table = data_table( idx1 | idx2, :)
4 个评论
Peter Perkins
2023-11-17
In addition to what Dyuman showed, I would recommend using string, not cell arrays of char row vectors, to store text, which allows you to use your original thought:
Rec_id =[1; 1; 2; 2; 2; 3; 3; 4; 4]; % for clarification: the values here go up to 80 in the original table
Rec_type= ["A";"B";"A";"B";"C";"A";"C";"A";"B"];
data_table = table(Rec_id, Rec_type);
data_table(data_table.Rec_type=="B",:)
Even better would be to use categorical for those data, since you have a small number of values, each repeated a bunch of times:
data_table.Rec_type = categorical(data_table.Rec_type)
categories(data_table.Rec_type) % for historical reasons this returns a cellstr
data_table(data_table.Rec_type=="B",:)
In this toy example it makes little difference, in large problems it makes a big difference.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Reference Applications 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!