007 Stata循环:forvalues

您所在的位置:网站首页 stata中lname 007 Stata循环:forvalues

007 Stata循环:forvalues

2023-05-09 10:47| 来源: 网络整理| 查看: 265

Stata中的循环有三类:

while循环 foreach循环 forvalues循环 其中,foreach和forvalues都可以看作是while循环的变种。两者的区别在于foreach跟的对象可以是宏、变量名和文件名等,而forvalues跟的必须是数字。

最后我们介绍 forvalues 循环

forvalues lname = range { Stata commands referring to `lname' } where range is #1(#d)#2 meaning #1 to #2 in steps of #d #1/#2 meaning #1 to #2 in steps of 1 #1 #t to #2 meaning #1 to #2 in steps of #t - #1 #1 #t : #2 meaning #1 to #2 in steps of #t - #1 The loop is executed as long as calculated values of `lname' are < #2, assuming that #d > 0. Braces must be specified with forvalues, and 1. the open brace must appear on the same line as forvalues; 2. nothing may follow the open brace except, of course, comments; the first command to be executed must appear on a new line; 3. the close brace must appear on a line by itself. *示例1 clear set obs 100 gen x1 = rnormal() gen x2 = rnormal() gen x3 = rnormal() gen x4 = rnormal() gen x5 = rnormal() forvalues i = 1(1)5 { disp "" disp "" disp "T-test: the mean of variable x`i' is 0" ttest x`i' = 0 } *示例2 clear cap mkdir C:\Users\Van\Desktop\download\paper cd C:\Users\Van\Desktop\download\paper forvalues i = 26068(1)26072 { cap copy https://www.nber.org/papers/w`i'.pdf w`i'.pdf, replace while _rc != 0 { disp "w`i'下载失败,10秒后重新下载" sleep 10000 cap copy http://www.nber.org/papers/w`i'.pdf w`i'.pdf, replace } disp "w`i'下载完成" }

此处解释下cap和_rc。cap有两个作用:一是不显示结果,类似于qui,二是即使所在行的命令有问题也可继续执行后续命令。_rc是stata运行cap命令时生成的一个系统标量,如果命令未出错,则_rc值为0,且该命令执行;若该命令出错,则_rc值为对应的错误代码,且该命令不执行。

参考资料: 官方帮助文档 【爬虫俱乐部】精通Stata之数据整理 stata 编程里 开头的capture 是什么意思?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3