##以下代码为stata中代码* Author:SUE
* Date:2020-10-09*1.while
capture drop count5
program count5
local i=1while `i' <=5{
di `i'
local i = `i'+1}
end
count5
*2.forvalues
forvalues i=1/5{
di `i'
}
forvalues i=4(-0.2)0{
di `i'
}
scalar s=0
forvalues i=1/100{
scalar s=s+`i'
}
scalar list s
*3.foreach
* 对变量循环
use infnt_00.dta,clear
foreach v of varlist IDind-T5{
tab `v'
}* 对文件循环
* 对字符列表循环
local grains " rice wheat flat maize "
foreach x of local grains{
di"`x'"}global money "dollar lira pound rmb"
foreach y of global money{
di "`y'"}* ?what's the difference of "local"and"global"* 生成新变量:变量名为b1-b5,10个观察期
clear
set obs 10
foreach v of newlist b1-b5{
gen `v'=uniform()}* 对数值列表循环
foreach num of numlist 1/48105{
dis `num'
}*4.nested
clear
set obs 10
forvalues i=1/5{
gen v`i'=.
forvalues j =1/10{
replace v`i'=`i'+`j' in `j'}}*5.if*5.1 simple
sysuse auto,clear
gen p1 = price -100if foreign ==0
replace p1 = price +100if foreign ==1* 或简写为(cond(x,a,b),若满足x,则执行a,否则执行b)
gen p2 = cond(foreign ==0,(price -100),(price +100))
capture program drop odd
program odd
args num
if mod(`num',2)!=1{
di "`num' is NOT an odd number"}else{
di "`num' is an odd number"}
end
* ?书上判断奇偶数的方法很奇特
capture program drop odd
program odd
args num
ifint(`num'/2) != (`num'-1)/2{
di "`num' is NOT an odd number"}else{
di "`num' is an odd number"}
end
capture program drop check
program check
capture confirm variable `l'
if_rc !=0{
di "`l' not found"
exit
}
di "the variable `l' exists"
end
* ?error : if_rc is unrecognized
*5.2 循环套条件
forvalues x =6/500{if mod(`x',2) == 0 & mod(`x',3)==0& mod(`x',5)==0{
di "the ALL common multiple of 2,3,and 5 is `x'."}}