Clear Filters
Clear Filters

Row with minimum value for each group in table

4 views (last 30 days)
HE
HE on 4 May 2020
Edited: HE on 5 May 2020
I want to group my table by one or more variables and find the minimum value for each group. Additionally I want to return other variables corresponding to that minimum value, e.g. the complete row of that minimum value.
grpstats or findgoups+splitapply does the job for the first step, but how do I return the corresponding row or corresponding values of other Variables?
edit: This is what I came up with. It works for me, suggestions are welcome.
load hospital
dsa = hospital(:,{'Sex','Age','Weight','Smoker'});
dst = dataset2table(dsa);
t = minrowingroup(dst,{'Sex','Smoker'},{'Age','Weight'})
function out = minrowingroup(tbl,groupBy,sortBy)
tbl.tempGroup = findgroups(tbl(:,groupBy));
out = table();
for i = 1: max(tbl.tempGroup)
p = tbl(tbl.tempGroup == i,:);
p = sortrows(p,sortBy);
out = [out; p(1,:)];
end
out.tempGroup = [];
end

Answers (0)

Categories

Find more on Tables in Help Center and File Exchange

Tags

Products


Release

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!