Hello. I wanted to use a global macro to assign a variable list, and called the list with the foreach var of varlist command. However, I am getting error messages.
Interestingly, when I run the same codes with my existing do file, they works well. However, when I start a new do file with the codes, it is not working. I want to know what I missed.
Thank you for your time.
The error message is: "mpg trunk turn invalid name
Here are my codes with the auto data:
-------------------------------
* data
sysuse auto, clear
* testing a loop command logging mode values
tab mpg
tab turn
tab trunk
* a list of variables
global testvar "mpg trunk turn"
di "$testvar"
* generate an excel file
putexcel set "test", replace
putexcel A1=("This Excel file shows the mode values for the selected variables")
* variable names
putexcel A3=("Name")
putexcel B3=("Mode")
local varnamerow = 4
foreach var of varlist "$testvar" {
quietly ds `var'
local varname r(varlist)
putexcel A`varnamerow'=(`varname')
quietly egen temp = mode(`var')
quietly sum temp
quietly local modeval = `r(mean)'
putexcel B`varnamerow'=(`modeval')
drop temp
local varnamerow = `varnamerow' + 1
}
putexcel close
Interestingly, when I run the same codes with my existing do file, they works well. However, when I start a new do file with the codes, it is not working. I want to know what I missed.
Thank you for your time.
The error message is: "mpg trunk turn invalid name
Here are my codes with the auto data:
-------------------------------
* data
sysuse auto, clear
* testing a loop command logging mode values
tab mpg
tab turn
tab trunk
* a list of variables
global testvar "mpg trunk turn"
di "$testvar"
* generate an excel file
putexcel set "test", replace
putexcel A1=("This Excel file shows the mode values for the selected variables")
* variable names
putexcel A3=("Name")
putexcel B3=("Mode")
local varnamerow = 4
foreach var of varlist "$testvar" {
quietly ds `var'
local varname r(varlist)
putexcel A`varnamerow'=(`varname')
quietly egen temp = mode(`var')
quietly sum temp
quietly local modeval = `r(mean)'
putexcel B`varnamerow'=(`modeval')
drop temp
local varnamerow = `varnamerow' + 1
}
putexcel close
Comment