Hi everyone,
I want to create a loop that calculates different values for some variables, depending on them being part of local list or not. If they are part of the list, I want Stata to count the observations with certain expressions of this variable. If they are not part of the list, Stata is supposed to calculate the share of observations that have the expression of this variable. Afterwards, the results are supposed to be put into excel, into different sheets depending on the variable.
It is necessary to do it in a loop since I want to repeat the same calculation for many variables and under several conditions ( not only dezil == `x' but also for other variables)
I tried to run this code and no matter how I adjust it, it always says invalid syntax. Can someone see the mistake or do you have a better idea of how to improve the loop?
I want to create a loop that calculates different values for some variables, depending on them being part of local list or not. If they are part of the list, I want Stata to count the observations with certain expressions of this variable. If they are not part of the list, Stata is supposed to calculate the share of observations that have the expression of this variable. Afterwards, the results are supposed to be put into excel, into different sheets depending on the variable.
It is necessary to do it in a loop since I want to repeat the same calculation for many variables and under several conditions ( not only dezil == `x' but also for other variables)
I tried to run this code and no matter how I adjust it, it always says invalid syntax. Can someone see the mistake or do you have a better idea of how to improve the loop?
Code:
global Auswertung_All ="anzPedrund anzCarsharing nocar quali_opnv bus28 bahn28 tram28 "
local row = 3
local ncol = 2
local vars = "nocar quali_opnv bus28 bahn28 tram28"
foreach var of "$Auswertung_All" {
foreach x of numlist 1/10 {
if `: list var in vars' {
tab `var' [aweight=h_hoch] if dezil==`x', matcell(freq) matrow(names)
local col : word `ncol' of `c(ALPHA)'
putexcel set "$outputExcel" , sheet("`var'_Sum") modify
putexcel `col'`row'=matrix(freq)
local ++ncol
}
else {
tab `var' [aweight=h_hoch] if dezil==`x', matcell(freq) matrow(names)
local col : word `ncol' of `c(ALPHA)'
putexcel set "$outputExcel" , sheet("`var'") modify
putexcel `col'`row'=matrix(freq/r(N))
local ++ncol
}
}
}

Comment