Matlab: Explicit Or Named Association Of `splitapply` Arguments With Table Variablenames
Solution 1:
This "answer" doesn't directly deal with explicit named association between the actual input/output variables and the arguments of the function handle supplied to splitapply. However, it significantly simplifies the code in the initial example, hopefully making it clearer to see the relationship between the function arguments and the input/output variables. This solution was initially included in the AFTERNOTE in the question. Since better answers don't appear to be forthcoming soon, I've decided to hive it out as the answer. It uses deal to implement an anonymous multiple-output function for splitapply to use on the data groups that are delineated by its grouping argument.
% Create test datatDat= array2table( floor(10*rand(5,3)) , ...
'VariableNames',{'x','y','z'} );
tDat.vGrouping = ( rand(5,1) > 0.5 )
% Find the groups
[ vGroup, ssRollups.grps ] = findgroups(tDat.vGrouping)
% Calculate summary metrics for each group of datafRollup= @(a,b,c) deal( mean(a-b), var(b+c) )
[ ssRollups.rollup1 ssRollups.rollup2 ] = ...
splitapply( fRollup, tDat(:,{'x','y','z'}), vGroup );
% Display use nice table formatting
struct2table( ssRollups )Until a better solution emerges, this approach will be my go-to idiom for splitapply.
Here is a variation that uses a table variable for the output of splitapply. This might be more convenient when using multiple grouping variables because findgroups will pass the grouping variable names to the output variable tRollups on the LHS:
% Create test datatDat= array2table( floor(10*rand(8,3)) , ...
'VariableNames',{'x','y','z'} );
tDat = [ tDat ...
array2table( rand(8,2)>0.5 , ...
'VariableNames',{'vGrpng1','vGrpng2'} ) ];
% Find the groups
[ vGroup, tRollups ] = findgroups(tDat(:,{'vGrpng1','vGrpng2'}));
% Calculate summary metrics for each group of datafRollup= @(a,b,c) deal( mean(a-b), var(b+c) )
[ tRollups.rollup1 tRollups.rollup2 ] = ...
splitapply( fRollup, tDat(:,{'x','y','z'}), vGroup );
tRollups
And here is a version that uses multiple grouping variables and uses a scalar struct instead of a table for the outputs of findgroup and splitapply:
% Create test datatDat= array2table( floor(10*rand(8,3)) , ...
'VariableNames',{'x','y','z'} );
tDat.vGrpng1 = rand(8,1)>0.5 ;
tDat.vGrpng2 = rand(8,1)>0.5
% Find the groups
[ vGroup, ssRollups.vGrpng1, ssRollups.vGrpng2 ] = ...
findgroups( tDat.vGrpng1, tDat.vGrpng2 );
% Calculate summary metrics for each group of datafRollup= @(a,b,c) deal( mean(a-b), var(b+c) )
[ ssRollups.rollup1 ssRollups.rollup2 ] = ...
splitapply( fRollup, tDat(:,{'x','y','z'}), vGroup );
% Display using nice table formatting
struct2table( ssRollups )
Post a Comment for "Matlab: Explicit Or Named Association Of `splitapply` Arguments With Table Variablenames"