Row with minimum value for each group in table
4 次查看(过去 30 天)
显示 更早的评论
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
回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!