Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Loop in Stata: Question about syntax

    I'm trying to do a loop over two major variables that I will show you in the following code:

    Code:
    forvalues i = 2/4 {
    *
    local ba_hes Bachelor_hes
    local res_field    restricted_field
    foreach c of local ba_hes  {
        forvalues j = 2/5             {
        foreach d of local res_field       {
                    svy,subpop(`c'`i' if `d'`j' == 1):prop k_uebertritt2
                }
            }
        }
    }
    Basically, I want to do the following thing:

    Code:
    svy,subpop(Bachelor_hes2 if restricted_field2 == 1) : prop k_uebertritt2
    svy,subpop(Bachelor_hes2 if restricted_field3 == 1) : prop k_uebertritt2
    svy,subpop(Bachelor_hes2 if restricted_field4 == 1) : prop k_uebertritt2
    svy,subpop(Bachelor_hes2 if restricted_field5 == 1) : prop k_uebertritt2
    up to...
    svy,subpop(Bachelor_hes4 if restricted_field5 == 1) : prop k_uebertritt2
    Rather than:

    Code:
    svy,subpop(Bachelor_hes2 if restricted_field1 == 1) : prop k_uebertritt2
    svy,subpop(Bachelor_hes3 if restricted_field1 == 1) : prop k_uebertritt2
    svy,subpop(Bachelor_hes4 if restricted_field1 == 1) : prop k_uebertritt2
    up to...
    svy,subpop(Bachelor_hes2 if restricted_field5 == 1) : prop k_uebertritt2
    svy,subpop(Bachelor_hes3 if restricted_field5 == 1) : prop k_uebertritt2
    svy,subpop(Bachelor_hes4 if restricted_field5 == 1) : prop k_uebertritt2
    Could anyone explain me the difference between these two methods mentioned above and their diferent syntaxes please?
    I'm also open to suggestions that improve my code above. Thanks for the feedback.

    Michael

  • #2
    Code:
    forval i= 2/5{
        forval j=2/5{
            svy,subpop(Bachelor_hes`i' if restricted_field`j' == 1) : prop k_uebertritt2
        }
    }

    Comment


    • #3
      Thanks Andrew!

      Comment


      • #4
        One moral here is that a loop over one item is not a loop that is needed.

        Another moral is that putting stuff into a local macro only to take it again immediately is also not needed.

        That said, if you're writing loops and just first testing your code tentatively with a simple case, and intending to generalise next, then go ahead, but the principles above still apply.

        Comment


        • #5
          Thanks Nick for the feedback.

          --
          Michael

          P.S.: I received the book "One hundred nineteen stata tips" today. Looking forward to learning more about good programming!

          Comment

          Working...
          X