Announcement

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

  • Problem with looping for a range

    Hi

    I have been trying to clean a dataset. In this dataset there are 29 variables named g1 g2....g29. Now, we expect that if g29==1 then all other varibales from g28 to g1 will be equal to 1 as well. Same is true for all other variables. For example, if g24==1 then g23, g22,......g1==1. I am trying to run a check if this holds true in the dataset. The command I have been using is this:

    list hhid if g29==1 & g28/1!=1
    list hhid if g28==1 & g27/1!=1
    list hhid if g27==1 & g26/1!=1
    list hhid if g26==1 & g25/1!=1
    ................

    So I have to go all the way down to g1 by doing this. I wanted to know if there is any way to loop this whole thing. I tried a few things like

    forval i=1/29{
    list hhid if g`i'==1 & g`i'-1/1!=1
    }

    But this does not work

    Is there any way to do this?

    Thanks so much

  • #2
    You can make a second macro, J1 = `J'-1:
    Code:
    forvalues J=2/29 {
       local J1 = `J'-1
       list hhid g`J' g`J1' if g`J'==1 & g`J1' != 1
    }

    Comment


    • #3
      There are other ways to look at this. One is that if every value of 29 is 1, then the row total should be 29.

      Another is that you could keep track of the last value recorded as 1.

      Code:
       
      gen last1 = g1 == 1 
      
      forval j = 2/29 { 
          replace last1 = `j' if g`j' == 1 
      }

      Comment


      • #4
        Thank you so much Svend and Nick. You guys made my day.

        Comment


        • #5
          Thanks for the appreciation. Please note our strong preference for full real names here. FAQ Advice Section 6 explains why and how to change.

          Comment

          Working...
          X