loopsstatadta

Stata Loop for a series of actions on three separate dta files


I'm trying to create a loop within Stata to apply a series of actions (including a merge, replacing missing values, replacing a date variable, sorting, and saving) to 3 different dta files (menin.dta, Bmenin.dta, and nonBmenin.dta). Below I have copied how to complete these tasks without a loop, but I want to figure out how to loop this code for the sake of simplifying it.

use "C:\Users\Desktop\menin.dta",clear
merge 1:1 bene_id using Controls,nogenerate
replace menin= 0 if menin ==.
replace date= refdate if menin ==0 
sort bene_id
save "C:\Users\Desktop\menin2.dta",replace

use "C:\Users\Desktop\Bmenin.dta",clear
merge 1:1 bene_id using Controls,nogenerate
replace Bmenin= 0 if Bmenin ==.
replace date= refdate if Bmenin ==0 
sort bene_id
save "C:\Users\Desktop\Bmenin2.dta",replace

use "C:\Users\Desktop\nonBmenin.dta",clear
merge 1:1 bene_id using Controls,nogenerate
replace nonBmenin= 0 if nonBmenin ==.
replace date= refdate if nonBmenin ==0 
sort bene_id
save "C:\Users\Desktop\nonBmenin2.dta", replace

Solution

  • This should do what you ask for:

    foreach data_name in menin Bmenin nonBmenin {
        use "C:\Users\Desktop\\`data_name'.dta", clear
        merge 1:1 bene_id using Controls, nogenerate
        replace `data_name'= 0 if `data_name' == .
        replace date = refdate if `data_name' == 0 
        sort bene_id
        save "C:\Users\Desktop/`data_name'2.dta", replace
    }
    

    Note that a ` is escaped if following immediately after a \ so you need to either do \\` or /`. I used one of each in the code example above. Best practice is to only use / as that would make this code run on Linux and Mac computers as well, but then you would have to update your hard coded file path anyways.