【发布时间】:2016-07-06 13:45:31
【问题描述】:
我有一个 Stata 数据集列表:其中一些变量 tor 不存在,如果它不存在,我想添加该变量。
数据集包含一个名为 xclass 的变量,其中 x 可以是任何东西(例如 Aclass、lclass 等)。我想rename那些变量到dec。
我想创建一个变量adjusted,如果文件名包含adjusted,则为"yes",否则为"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")
}
【问题讨论】:
-
查看similar question 的这些答案,了解存储和读取文件名的方法。
-
本地
myfilelist没有定义,所以循环什么也不做。应该是filelist。
标签: database loops variables stata renaming