how to assign same value according to each subgroup

조회 수: 1 (최근 30일)
Hyein Han
Hyein Han 2020년 5월 31일
댓글: Ameer Hamza 2020년 5월 31일
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!
Ameer Hamza
Ameer Hamza 2020년 5월 31일
I am glad to be of help!

댓글을 달려면 로그인하십시오.

추가 답변 (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