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 Center および File ExchangeMarine and Underwater Vehicles についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by