stata:stata软件教程(人大十八讲)(7) 第七章 流程语句(循环)

第七章 流程语句

##以下代码为stata中代码
* Author:SUE
* Date:2020-10-09

* 1.while
capture drop count5

program count5
local i=1
while `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/4 8 105{
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 - 100 if foreign == 0
replace p1 = price + 100 if 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
if int(`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'."
}
}
  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值