我有一个Stata数据集列表:其中一个变量tor
不存在,我想添加该变量(如果它不存在)。在Stata文件列表中重命名和创建变量
该数据集包含一个称为Xclass
其中X可以是任何东西(例如Aclass
,lclass
等)可变。我想rename
这些变量为dec
。
我想创建一个变量adjusted
这是"yes"
如果文件名包含adjusted
和"no"
如果不是。
我想这将是这个样子:
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
}
但随后在适当的Stata的语言。
所以,现在我已经得到了这一点,但它不工作,它不会做什么...
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")
}
看看这些答案的[类似问题](http://stackoverflow.com/questions/37845840/parsing-through-all-folders-in-a-目录)的方法来存储和阅读文件名称。 – lmo
本地'myfilelist'没有定义,所以循环什么都不做。应该是'filelist'。 –