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 个)

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

标签

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by