how to assign same value according to each subgroup

1 view (last 30 days)
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!

Accepted Answer

Ameer Hamza
Ameer Hamza on 31 May 2020
Edited: Ameer Hamza on 31 May 2020
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 Comments
Hyein Han
Hyein Han on 31 May 2020
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!

Sign in to comment.

More Answers (0)

Categories

Find more on Marine and Underwater Vehicles in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!