how to assign same value according to each subgroup

1 次查看(过去 30 天)
Hello, I'd like to generate new variable, say, classid2
My dataset looks like the following:
school classid
11005 1
11005 2
11006 1
11006 2
11009 1
11010 1
11010 2
11013 1
11013 2
11013 3
11015 1
11015 2
11015 3
11017 2
11017 1
11020 1
11020 2
----------------------------------------------------
each school has different number of classes, (can be 1, 2, or 3) and Ssize is number of students each class has. What I want is new variable classid2, which is the maximum value of classid for each school such as the following,
school classid classid2
11005 1 2
11005 2 2
11006 1 2
11006 2 2
11009 1 1
11010 1 2
11010 2 2
11013 1 3
11013 2 3
11013 3 3
11015 1 3
11015 2 3
11015 3 3
11017 2 2
11017 1 2
11020 1 2
11020 2 2
I cannot come up with how to state using if or for loop, or maybe rearrange the arrays?
Thanks in advance!

采纳的回答

Ameer Hamza
Ameer Hamza 2020-5-31
编辑:Ameer Hamza 2020-5-31
Try this
M = [
11005 1
11005 2
11006 1
11006 2
11009 1
11010 1
11010 2
11013 1
11013 2
11013 3
11015 1
11015 2
11015 3
11017 2
11017 1
11020 1
11020 2];
school = M(:,1);
classID1 = M(:,2);
grps = findgroups(school);
max_vals = splitapply(@max, classID1, grps);
classID2 = max_vals(grps);
Result
>> classID2
classID2 =
2
2
2
2
1
2
2
3
3
3
3
3
3
2
2
2
2
  2 个评论
Hyein Han
Hyein Han 2020-5-31
WOW, yes it really worked. I couldn't proceed further from splitapply function, and your "ClassID2 = max_vals(grps)" command helped me to resolve this. Thanks a lot!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Marine and Underwater Vehicles 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by