美文网首页stata小小白
006 Stata循环:foreach

006 Stata循环:foreach

作者: 凡有言说 | 来源:发表于2019-07-16 09:02 被阅读1次

    Stata中的循环有三类:

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

    接下来我们介绍 foreach循环

       foreach lname {in|of listtype} list {
                    commands referring to `lname'
            }
    
      Allowed are
    
            foreach lname in any_list {
    
            foreach lname of local    lmacname   {
    
            foreach lname of global   gmacname   {
    
            foreach lname of varlist  varlist    {
    
            foreach lname of newlist  newvarlist {
    
            foreach lname of numlist  numlist    {
    
        Braces must be specified with foreach, and
    
            1.  the open brace must appear on the same line as the foreach;
    
            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()
    
    foreach var in x1 x2 x3 x4 x5{
        disp ""
        disp ""
        disp "T-test: the mean of variable `var' is 0"
        ttest `var' = 0
    }
    
    
    *示例2
    sysuse auto, clear
    
    foreach v in mpg weight length{
        summarize `v'
    }
    

    在foreach循环中,如果选择所有变量,可以写成:

    foreach var of varlist_all{
        command
    }
    
    或
    
    foreach var of varlist * {
        command
    }
    

    参考资料
    官方帮助文档
    【爬虫俱乐部】精通Stata之数据整理

    相关文章

      网友评论

        本文标题:006 Stata循环:foreach

        本文链接:https://www.haomeiwen.com/subject/cpyvkctx.html