Hello,
Can anyone suggest a way to use a loop to replace values in several variables with conditions? Here is the situation.
I created seven variables (years in which an outcome is measured); named these as ys_prot_at`year'. Each of these variables will have a value equal to:
the number of years an observation (my rows) has been treated (protected, with variable name as year_pa) minus the year of the outcome measure (corresponding to the year in ys_prot_at`year') plus 1; I wan to account cases the year of the outcome = the year of initial treatment to be at least 1 to avoid having 0 for treated units. The value in ys_prot_at`year' would be 0 if the observation has not been protected in the given year of the outcome measure. This is a panel dataset.
The code below works to get what I need but I couldn't do this using a loop; I am not sure if using a loop is possible to get the result I wanted? I don't think sharing a sample dataset is necessary so I am assuming my description will do for now. Please let me know if you know a way to using a loop in a situation like the one I tried to describe.
Thanks in advance,
Carlos
foreach year of numlist 1986 1991 1996 2001 2003 2011 2016 {
gen ys_prot_at`year' = 0
label variable ys_prot_at`year' "years protected by `year'"
}
replace ys_prot_at1986 = cond(year_pa == 1956, -1956+1986+1, 0)
replace ys_prot_at1991 = cond(year_pa == 1956, -1956+1991+1, cond(year_pa == 1987, -1987+1991+1, 0))
replace ys_prot_at1996 = cond(year_pa == 1956, -1956+1996+1, cond(year_pa == 1987, -1987+1996+1, cond(year_pa == 1994, -1994+1996+1, 0)))
replace ys_prot_at2001 = cond(year_pa == 1956, -1956+2001+1, cond(year_pa == 1987, -1987+2001+1, cond(year_pa == 1994, -1994+2001+1, cond(year_pa == 1998, -1998+2001+1, cond(year_pa == 1999, -1999+2001+1, 0)))))
replace ys_prot_at2003 = cond(year_pa == 1956, -1956+2003+1, cond(year_pa == 1987, -1987+2003+1, cond(year_pa == 1994, -1994+2003+1, cond(year_pa == 1998, -1998+2003+1, cond(year_pa == 1999, -1999+2003+1, cond(year_pa == 2003, -2003+2003+1, 0))))))
replace ys_prot_at2011 = cond(year_pa == 1956, -1956+2011+1, cond(year_pa == 1987, -1987+2011+1, cond(year_pa == 1994, -1994+2011+1, cond(year_pa == 1998, -1998+2011+1, cond(year_pa == 1999, -1999+2011+1, cond(year_pa == 2003, -2003+2011+1, cond(year_pa == 2006, -2006+2011+1, cond(year_pa == 2007, -2007+2011+1, cond(year_pa == 2009, -2009+2011+1, cond(year_pa == 2010, -2010+2011+1, 0))))))))))
replace ys_prot_at2016 = cond(year_pa == 1956, -1956+2016+1, cond(year_pa == 1987, -1987+2016+1, cond(year_pa == 1994, -1994+2016+1, cond(year_pa == 1998, -1998+2016+1, cond(year_pa == 1999, -1999+2016+1, cond(year_pa == 2003, -2003+2016+1, cond(year_pa == 2006, -2006+2016+1, cond(year_pa == 2007, -2007+2016+1, cond(year_pa == 2009, -2009+2016+1, cond(year_pa == 2010, -2010+2016+1, 0))))))))))
0 Response to Help using loop to replace values in several variables with conditions
Post a Comment