Looping over value/variables/files are some key time-saving tricks. Hope this could help.
forval i = 2/10 {
gen byte year`i' = (year == `i')
}
Loop over ordered variables (var1,var2,…varN)
*i.e. interested variables in precise order
foreach v of varlist var1-varN{
gen new`v' = `v'*100
}
local bn = 1000000000 // simply a cosmetic touch
foreach v in "1" "5" "x" "y" "N" {
replace var`v' = var`v'/`bn'
la var var`v' "Group `v', in billion"
}
ds v1 v2, not // excluding v1 and v2 from all variable
global looplist `r(varlist)' // this stores your desired variable list
foreach v of varlist $looplist{
[commands]
}
More about ds command, see: Alain Vandormael
Loop over files within a folder (file1, file2, … fileN) *credit to Andreas Ebbehoj
* 1) Locate the target directory
*(the folders are named 2010, 2011,..., 2021)
local filepath = "/Users/steve/Dropbox/IHEID/.../file/"
foreach i of num 2010/2021{
local files : dir "`filepath'`i'/" files "*.xls"
* 2) Loop over all files to import and append each file
tempfile master`i' // Generate temporary file to store data
save `master`i'', replace empty
cd "`filepath'`i'/"
foreach x of local files {
di "`x'" // Display file name
* 2A) Import each file
import excel "`x'", cellrange(A2) firstrow clear // Import excel file
gen id = subinstr("`x'", ".xls", "", .) // Generate id variable (same as file name but without .xls)
rename oldvar newvar
* 2B) Append each file to masterfile
append using `master`i''
save `master`i'', replace
}
}
Example in generate temperature difference in hottest-to-coldest, second-hottest-to-second-coldest, etc.
sort Country Year Temperature
loc x = 1
loc y = 12
forvalues i = 1/6{
by Country Year, sort: gen pair`i' = Temperature[`y'] - Temperature[`x']
loc x = `x'+1
loc y = `y'-1
}
Loop over values (1,2,…12)
Example in generating yearly dummies
Loop over unordered variables (var1,var5,…varN)
*i.e. interested variables NOT in precise order
Loop over all variables except a few
Loop over all alphabetic order
*for Stata 17 and onwards: local labels " "Model" "Country FE" "Obs." " *for older Stata version: local labels `" `"Model"' `"Country FE"' `"Obs."' "' esttab y x1 xN /// using ./table_ouput, /// . . stats(`stats_rows', /// fmt(`fmt_set') /// labels(`labels'))
tokenize `c(alpha)'
local alphabet = 1 // = a
forval i = 1/5 {
esttab result_`i' ///
using ./output/`file', append ///
title({\b Table 1.``alphabet''} ///
[other optional commands]
local alphabet = `alphabet'+1
}
Double-quote problem, example on stackoverflow
Save a list of row titles { “Model” “Country FE” etc… } and reuse them at every regression table output.