Announcement

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

  • IF condition within a loop depending on the iterated value of the loop

    I would appreciate any help that you can give on my question below.

    For example, I have the following loop:
    foreach var of varlist X1 X2 X3 {

    reg DV `var' control_set1
    reg DV `var' control_set2

    }

    I want to add an IF condition depending on the value of var.

    For example, for X2 and X3, add the condition “if fyear>2005”. The effect would be like this:

    reg DV X1 control_set1
    reg DV X1 control_set2

    reg DV X2 control_set1 if fyear>2005
    reg DV X2 control_set2 if fyear>2005

    reg DV X3 control_set1 if fyear>2005
    reg DV X3 control_set2 if fyear>2005

    Is it possible to do this in a loop?



  • #2
    absolutely,
    Code:
    foreach x in x1 x2 x3 {
    if `x'==x1 {
    reg dv `x'
    }
    else {
    reg dv `x' if fyear>2005
    }
    }

    Comment


    • #3
      The advice in #2 is not quite right. The test should be on the names, not the values of the variables. The code in #2 might work by accident as x1 == x1 but if x2 = x1 or x3 = x1 in the first observation (which is all that would be tested) then the code will not work as desired.

      Consider rather

      Code:
      foreach x in x1 x2 x3 {
      if "`x'"=="x1" {
      reg dv `x'
      }
      else {
      reg dv `x' if fyear>2005
      }
      }
      In the example given, it would be even simpler to go

      Code:
      reg dv x1 
      
      foreach x in x2 x3 { 
          reg dv `x' if fyear>2005
      }
      and indeed I see no great virtue in a loop at all as compared with three plain regress statements. Naturally, your full or real example may be much more complicated.

      Comment


      • #4
        Thank you so much Øyvind and Nick.

        Indeed my code inside the loop is much more complicated than the example I give above and so I wish to use a loop.

        Comment

        Working...
        X