Hi all, using the data below, I am trying to figure out how to write a foreach loop that does what I've done in clunky fashion here.
Basically, I want to create a variable that captures whether a student was tested before a given age. But I also want to only keep students in the "0" group if they are never tested, or if they are not tested until they're 19. So the 0 condition is actually the same on all of these variables--the part I can't figure out is how to best tell Stata I want testedbefore_x to = 1 if testedx-1_w1 == 1, or testedx-2_w1 == 1, and so on down to 10. If anyone has any ideas I'd be very appreciative!
Basically, I want to create a variable that captures whether a student was tested before a given age. But I also want to only keep students in the "0" group if they are never tested, or if they are not tested until they're 19. So the 0 condition is actually the same on all of these variables--the part I can't figure out is how to best tell Stata I want testedbefore_x to = 1 if testedx-1_w1 == 1, or testedx-2_w1 == 1, and so on down to 10. If anyone has any ideas I'd be very appreciative!
Code:
gen testedbefore_15 = . replace testedbefore_15 = 0 if test == 0 | (inrange(age_firsttest, 19, 25)) replace testedbefore_15 = 1 if inlist(1, tested10_w1, tested11_w1, tested12_w1, tested13_w1, tested14_w1) gen testedbefore_16 = . replace testedbefore_16 = 0 if test == 0 | (inrange(age_firsttest, 19, 25)) replace testedbefore_16 = 1 if inlist(1, tested10_w1, tested11_w1, tested12_w1, tested13_w1, tested14_w1, tested15_w1) gen testedbefore_17 = . replace testedbefore_17 = 0 if test == 0 | (inrange(age_firsttest, 19, 25)) replace testedbefore_17 = 1 if inlist(1, tested10_w1, tested11_w1, tested12_w1, tested13_w1, tested14_w1, tested15_w1, tested16_w1) gen testedbefore_18 = . replace testedbefore_18 = 0 if test == 0 | (inrange(age_firsttest, 19, 25)) replace testedbefore_18 = 1 if inlist(1, tested10_w1, tested11_w1, tested12_w1, tested13_w1, tested14_w1, tested15_w1, tested16_w1, tested17_w1)
Code:
* Example generated by -dataex-. For more info, type help dataex clear input byte(tested10_w1 tested11_w1 tested12_w1 tested13_w1 tested14_w1 tested15_w1 tested16_w1 tested17_w1 tested18_w1 age_firsttest test) float(testedbefore_15 testedbefore_16 testedbefore_17 testedbefore_18) 0 0 0 0 0 0 1 0 0 16 1 . . 1 1 0 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