Stata foreach循环从变量名列表中生成新变量
Stata foreach loop to generate new variables from a list of variable names
我想创建一个循环,它创建虚拟变量并从变量名称列表中命名它们,然后在所有变量名称都被迭代一次后停止。
我的尝试:
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
}
}
}
我感觉到你对
感到困惑
Stata 意义上的局部宏和变量(虽然 c
机制是合法的,但局部宏更适合用作计数器,除非你根本不需要一个)
generate
和 replace
因为您正在尝试 generate
已经存在的变量
并行循环,不是嵌套循环
(对我而言)有点不清楚的正是您想要做的。
我想这就是你想要的。
您有 11 个现有变量。
你要11个对应的新变量,如果对应的现有变量是2或3,则每个变量是一个指标1,如果是1,则为0,否则为缺失。
如果是这样,这就是代码草图。注意:这只是一个循环。
local newvars teacher_late teacher_absent teacher_skip teacher_bully teacher_harass_teachers teacher_harass_pupils teacher_language teacher_drugs teacher_alcohol teacher_health teacher_conflict
foreach x of varlist stchpr01-stchpr11 {
gettoken new newvars : newvars
gen `new' = cond(`x' == 2 | `x' == 3, 1, cond(`x' == 1, 0, .))
}
另见 https://journals.sagepub.com/doi/pdf/10.1177/1536867X211063415
我想创建一个循环,它创建虚拟变量并从变量名称列表中命名它们,然后在所有变量名称都被迭代一次后停止。
我的尝试:
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
}
}
}
我感觉到你对
感到困惑Stata 意义上的局部宏和变量(虽然
c
机制是合法的,但局部宏更适合用作计数器,除非你根本不需要一个)generate
和replace
因为您正在尝试generate
已经存在的变量并行循环,不是嵌套循环
(对我而言)有点不清楚的正是您想要做的。
我想这就是你想要的。
您有 11 个现有变量。
你要11个对应的新变量,如果对应的现有变量是2或3,则每个变量是一个指标1,如果是1,则为0,否则为缺失。
如果是这样,这就是代码草图。注意:这只是一个循环。
local newvars teacher_late teacher_absent teacher_skip teacher_bully teacher_harass_teachers teacher_harass_pupils teacher_language teacher_drugs teacher_alcohol teacher_health teacher_conflict
foreach x of varlist stchpr01-stchpr11 {
gettoken new newvars : newvars
gen `new' = cond(`x' == 2 | `x' == 3, 1, cond(`x' == 1, 0, .))
}
另见 https://journals.sagepub.com/doi/pdf/10.1177/1536867X211063415