how to assign same value according to each subgroup

1 visualización (últimos 30 días)
Hyein Han
Hyein Han el 31 de Mayo de 2020
Comentada: Ameer Hamza el 31 de Mayo de 2020
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!

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 31 de Mayo de 2020
Editada: Ameer Hamza el 31 de Mayo de 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 comentarios
Hyein Han
Hyein Han el 31 de Mayo de 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!
Ameer Hamza
Ameer Hamza el 31 de Mayo de 2020
I am glad to be of help!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Marine and Underwater Vehicles en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by