I'm working with longitudinal data that, for every family unit observed, includes observations for both parents and children. I'm trying to code parental status, using the mother and father ID numbers (MOM_ID DAD_ID), and ages (AGE), attached to each respondent labeled a child (RELATE). Specifically, I want to create three new variables:

1. OWNKID: for each parent observation, count of all children in the family, regardless of age
2. OWNKID_18: for each parent observation, count of all children in the family younger than 18
3. OWNKID_5: for each parent observation, count of all children in the family younger than 5

Below is a sample of the data I'm trying to generate -- with the three variables I define above filled in with what I'm looking for. I've been trying to apply the loop suggested in number 6 on this page: https://www.stata.com/support/faqs/d...ng-properties/. But it's only able to generate a variable that tells me, 0/1, whether someone has a child (w/ my slight adjustments). And I'm not sure where in the loop to account for the child's age. Thank you for any help you can provide!

PERSON_ID FAMILY_ID Y_M WIFAM_PERSON_ID MOM_ID DAD_ID AGE RELATE OWNKID OWNKID_18 OWNKID_5
1234 101 2020_1 1 0 0 33 hh-head 1 1 1
1234 101 2020_2 1 0 0 33 hh-head 1 1 1
1234 101 2020_3 1 0 0 33 hh-head 1 1 1
1235 101 2020_1 2 0 0 35 spouse 1 1 1
1235 101 2020_2 2 0 0 35 spouse 1 1 1
1235 101 2020_3 2 0 0 35 spouse 1 1 1
1236 101 2020_1 3 1 2 4 child 0 0 0
1236 101 2020_2 3 1 2 4 child 0 0 0
1236 101 2020_3 3 1 2 4 child 0 0 0
1237 202 2020_1 1 0 0 49 hh-head 2 1 0
1237 202 2020_2 1 0 0 49 hh-head 2 1 0
1238 202 2020_1 2 0 0 54 spouse 2 1 0
1238 202 2020_2 2 0 0 54 spouse 2 1 0
1239 202 2020_1 3 1 2 19 child 0 0 0
1239 202 2020_2 3 1 2 19 child 0 0 0
1240 202 2020_1 4 1 2 16 child 0 0 0
1240 202 2020_2 4 1 2 16 child 0 0 0