I am attempting to create a loop to generate a new variable, but also need to create a second new variable based on the first new variable within that loop.
Specifically, I want to create and replace values for a new variable called 'med_x', where x represents a time-point that can equal values 1-20; the values of 'med_x' will be based on when the medication starts and stops in relation to 'month_y' and 'month_z', where y= x*3 and z = (x*3)-3. I could of course do this by hand by writing code out for values 1-20, but I know there is an easier way to code the logic. Any help figuring this out would be appreciated!
Here is an example if I were to code one time-point at a time:
gen med_4 = 1 if start_date_master <= month_12 & stop_date_master >= month_12
replace med_4 = 1 if start_date_master <= month_12 & stop_date_master < month_12 & stop_date_master > month_9
I am not sure if this requires a double loop (or loop within a loop), or if there is an easier process. I've also tried creating two local variables to reference within one loop, but either get no error (but no variable is produced), or an "invalid syntax" error. This is my latest attempt:
Here the error code I get is "invalid syntax."
Thanks in advance!!
Specifically, I want to create and replace values for a new variable called 'med_x', where x represents a time-point that can equal values 1-20; the values of 'med_x' will be based on when the medication starts and stops in relation to 'month_y' and 'month_z', where y= x*3 and z = (x*3)-3. I could of course do this by hand by writing code out for values 1-20, but I know there is an easier way to code the logic. Any help figuring this out would be appreciated!
Here is an example if I were to code one time-point at a time:
gen med_4 = 1 if start_date_master <= month_12 & stop_date_master >= month_12
replace med_4 = 1 if start_date_master <= month_12 & stop_date_master < month_12 & stop_date_master > month_9
I am not sure if this requires a double loop (or loop within a loop), or if there is an easier process. I've also tried creating two local variables to reference within one loop, but either get no error (but no variable is produced), or an "invalid syntax" error. This is my latest attempt:
Code:
local timepoint 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 foreach x of local timepoint { local month_period timepoint*3 foreach y of local month_period { gen med_`x' = 1 if start_date_master <= month_`y' & stop_date_master >= month_`y' replace med_`x' = 1 if start_date_master <= month_`y' & stop_date_master < month_`x' & stop_date_master > month_`y' } }
Thanks in advance!!
Comment