Announcement

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

  • Using If Statements within Foreach

    Hello everyone,

    I'm fairly new to STATA but this one issue has been driving me crazy...I would really appreciate any help...

    I'm trying to loop through a set of variables, and any variables that have a certain value will execute a series of if statements afterwards...however the if statement which determines if the value is met doesn't seem to be being read, or the program isn't entering that bracket for some reason. I've tested this by having a number (varno) displayed before and after the if statement in question...before it will work but after it won't. informant_type1-7 is a numeric variable with values 0-4

    gen varno = 1

    foreach informant of varlist informant_type1 informant_type2 informant_type3 informant_type4 informant_type5 informant_type6 informant_type7 {
    di varno
    if `informant' == 4 {
    di varno
    commands...
    }
    }

    Is there something wrong with the way I am setting this up?

    Many thanks for any advice!


  • #2
    The if command is not intended to be used as you have used it. Here is a FAQ that discusses this further.

    http://www.stata.com/support/faqs/pr...-if-qualifier/

    Comment


    • #3
      William is right. Let's push the point further.

      Code:
      foreach informant of varlist informant_type1 informant_type2 informant_type3 informant_type4 informant_type5 informant_type6 informant_type7 {
          di varno
          if `informant' == 4 {
               di varno
              commands...
          }
      }
      I guess what you want to code is something rather different:

      Code:
      foreach informant of varlist informant_type1 informant_type2 informant_type3 informant_type4 informant_type5 informant_type6 informant_type7 {
           count if `informant' == 4
           if r(N) > 0 {
                 ...
           }
           else ...
      }
      By the way. it's much simpler to write

      Code:
      forval j = 1/7 {
           count if informant_type`j' == 4
           if r(N) > 0 {
                 ...
           }
           else ...
      }

      Comment


      • #4
        That is super clear, thank you both!

        Comment


        • #5
          Note also that with findname (SJ) you could go

          Code:
          findname informant_type*, any(@ == 4)
          to find which of those variables had any values equal to 4.

          Comment

          Working...
          X