Announcement

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

  • Loop with consecutive numbers

    Hello Stata community,

    I am trying to replace multiple id of a data set, where the ids are consecutive numbers.

    What I need:

    replace new_id=149 if man==1 & count_man==1
    replace new_id=150 if man==1 & count_man==2
    replace new_id=151 if man==1 & count_man==3
    replace new_id=152 if man==1 & count_man==4
    replace new_id=153 if man==1 & count_man==5
    replace new_id=154 if man==1 & count_man==6
    replace new_id=155 if man==1 & count_man==7
    replace new_id=156 if man==1 & count_man==8
    replace new_id=157 if man==1 & count_man==9

    I have about 100 ids that need to be changed, therefore I am trying to run a loop. I have tried the following code, but it does not change anything


    local obs=1
    forvalues x=149/271 {
    forvalues i=1/117 {
    replace new_id= `x' if man==1 & count_man==`i' in `obs'
    }
    }

    Any suggestions?

    Best,

    Tatiana

  • #2
    A loop is not necessary for your case.

    Code:
    replace new_id = count_man + 148 if man == 1

    Comment


    • #3
      At first sight this calls for at most one loop, not two nested loops. Your code never does anything outside the first observation in any case.

      How about this?

      Code:
      replace new_id = count_man + 148 if man==1 & inrange(count_man, 1, 117)
      Here the loop is given by count_man + 148

      Code:
      in `obs'
      in your code was only ever

      Code:
      in 1
      But, but, but: 271 is not 148 + 117 so perhaps your problem is more complicated than your code implies.

      Comment

      Working...
      X