Stata foreach循环从变量名的列表中生成新变量
我希望创建一个循环,该循环创建虚拟变量并从可变名称列表中名称,然后在所有变量名称都迭代一次后停止。
我的尝试:
gen c = 0
foreach x of varlist stchpr01-stchpr11{
foreach i in teacher_late teacher_absent teacher_skip teacher_bully teacher_harass_teachers teacher_harass_pupils teacher_language teacher_drugs teacher_alcohol teacher_health teacher_conflict{
while c < 11{
gen `i' = 0
replace `i' = 1 if `x' == 2 | `x' == 3
replace `i' = 0 if `x' == 1
replace `i' = . if missing(`x')
replace c = c+1
}
}
}
I am looking to create a loop which creates dummy variables and names them from a list of variable names, and then stops once all variable names have been iterated over once.
My Attempt:
gen c = 0
foreach x of varlist stchpr01-stchpr11{
foreach i in teacher_late teacher_absent teacher_skip teacher_bully teacher_harass_teachers teacher_harass_pupils teacher_language teacher_drugs teacher_alcohol teacher_health teacher_conflict{
while c < 11{
gen `i' = 0
replace `i' = 1 if `x' == 2 | `x' == 3
replace `i' = 0 if `x' == 1
replace `i' = . if missing(`x')
replace c = c+1
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
我感觉到您在Stata的意义上在
本地宏和变量之间感到困惑
c
机械是合法的,但本地宏可以用作计数器,除了您不需要一个完全)生成> /code>和
替换
在您尝试生成
已存在的变量时
循环的变量,而不是嵌套循环
什么不清楚(对我来说)是您想做的。
我认为这就是您想要的。
您有11个现有变量。
您需要11个相应的新变量,如果相应的现有变量为2或3、0,则每个变量是指示1
如果是这样,这是一个代码草图。 NB:只是一个循环。
另请参见
I sense that you are getting confused between
local macros and variables in Stata's sense (although the
c
machinery is legal, local macros are better for use as counters, except that you don't need one at all)generate
andreplace
as you're trying togenerate
variables that already existloops in parallel, which are not nested loops
What is a little unclear (to me) is exactly what you want to do.
I take it this is what you want.
You have 11 existing variables.
You want 11 corresponding new variables, each of which is to be an indicator 1 if the corresponding existing variable is 2 or 3, 0 if it is 1, and missing otherwise.
If so, this is a code sketch. NB: it's just one loop.
See also https://journals.sagepub.com/doi/pdf/10.1177/1536867X211063415