我正在尋找創建一個回圈,該回圈創建虛擬變數并從變數名串列中命名它們,然后在所有變數名都被迭代一次后停止。
我的嘗試:
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
}
}
}
uj5u.com熱心網友回復:
我感覺到你在
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477850.html
上一篇:何在R中運行分層自舉線性回歸?
