I have a list of Stata datasets: among some a variable tor
is absent, and I want to add that variable if it doesn't exist.
The datasets contain a variable called xclass
where x could be anything (e.g. Aclass
, lclass
, etc.). I would like to rename
those variables to dec
.
I want to create a variable adjusted
which is "yes"
if the file name contains adjusted
and "no"
if not.
I guess it would look something like:
Loop through list of datasets and their variables {
if variable contains pattern class
rename to dec
if no variable tor, then
gen str tor = total
if file name contains pattern adjusted
gen str adjusted = yes
else gen str adjusted = no
}
But then in proper Stata language.
So I've got this now, but it's not working, it doesn't do anything...
cd "C:\Users\test"
local filelist: dir "." files "*.dta", respectcase
foreach filename of local myfilelist {
ds *class
local found `r(varlist)'
local nfound : word count `found'
if `nfound' == 1 {
rename `found' dec
}
else if `nfound' > 1 {
di as err "warning: multiple *class variables in `filename'"
}
capture confirm var tor
if !_rc == 0 {
gen tor = "total"
}
gen adjusted = cond(strpos("`filename'", "_adjusted_"), "yes", "no")
}
myfilelist
is not defined, so the loop does nothing. Should befilelist
. – Nick Cox