Index and select rows from table
8 views (last 30 days)
Show older comments
A table includes columns with numerical and categorical columns (see attachement)
How can I get multiple subtables based on the categories of a column (e.g., col5)?
Expected output: 4 different tables (table1includes rows with "h_001" in col5... table4 includes rows with "r_041" in col5)
I could not use the following option when the columns have categorical data:
https://ch.mathworks.com/matlabcentral/answers/481574-how-to-get-the-index-of-a-value-in-a-table
9 Comments
Stephen23
on 21 Nov 2023
Edited: Stephen23
on 21 Nov 2023
"I don't see how ismember() would be more efficient. It would require at least 2 lines per categorie"
Whatever way you do it, processing every category individually will be inefficient (in terms of your time writing and/or runtime).
That is why I suggested ISMEMBER, so that you can do all categories at once. Three lines of code, done.
Do not store each category individually. That is not how MATLAB works, you need to learn how to use vectors, matrices, and arrays. Start by placing all of the categories into one array (e.g. a string array), then use one ISMEMBER call. Read the ISMEMBER documentation carefully.
Another option would be to use one of the JOIN family.
Answers (1)
Peter Perkins
on 27 Nov 2023
"I need to split the original data based on the categories of col5."
You probably do not want/need to do that. Take a look at the rowfun function. Write a function to do what you want with each subset of your data, then use rowfun to apply that function based on groups defined by col5.
t = table([1;1;1;2;2;3;3;3],rand(8,1),rand(8,1),VariableNames=["G" "X" "Y"])
myFun = @(x,y) mean(x) - mean(y);
rowfun(myFun,t,GroupingVariables="G")
Lots of other functions, like groupsummary, similarly do not require you to split your data up. As others have said, that's usually a bad idea and unnecessary.
0 Comments
See Also
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!