Is There a Way to Execute splitapply Functionality on Subtables of Master Table?
Show older comments
Suppose I have a function that operates on a table and returns a row vector:
function rowvec = myfunc(Table)
Suppose I have a master table, call it T with one of its variables being Name. I'd like to do something like the following to group by Name and concatenate rowvec computed from each subgroup:
G = findgroups(T.Name);
R = splitapply(@myfunc,T,G);
This won't work because splitapply sends the group of each variable in T to myfunc and not the subtable of T defined by G.
Is there already a function that does what I'm trying to do?
Or do I have to use the code here: https://www.mathworks.com/matlabcentral/answers/457422-separate-table-data-in-to-sub-tables to generate the cell array of subtables, loop over the subtables with a call to myfunc, and then concatenate the rows myself? Or maybe use cellfun on the cell array of subtables?
2 Comments
dpb
on 10 May 2020
I don't follow what's wrong with splitapply?
Show us an example that doesn't do the right thing.
Answers (1)
Peng Li
on 10 May 2020
you'd better do this way:
splitapply(@(x) sum(x, 1), T{:, 2:3}, G);
5 Comments
Peng Li
on 11 May 2020
You shouldn’t use splitapply as it accepts matrix or cell array. Table is not a type that it accepts.
Another scenario, you have to feed splitapply a matrix or cell from you table. As long as you know which input is corresponding to for example the color property you can adapt your function that way. Will give an example later. Using cellphone now.
dpb
on 11 May 2020
" myfunc is more complicated and is expecting a table T with a certain structure"
That's not the input form splitapply expects for the function inputs for a table -- from the doc:
T — Data variables
table
Data variables, specified as a table. splitapply treats each table variable
as a separate data variable.
So, if your table has N columns, the function must accept N input variables; each of the appropriate type for those in the table by column.
Paul
on 11 May 2020
Peng Li
on 11 May 2020
It is not clear why you want to subtable your table before splitapply. splitapply is supposed to finish the job for you. Anyway, I'm happy that you found out the solution for your problem!
Categories
Find more on Data Type Conversion 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!