Announcement

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

  • loop

    Hi Everyone,

    I would like to use a loop for the following code:

    Code:
    gen var1=1 if x == y1 | x == y2 | x == y3| x == y4| x == y5| x == y6| x == y7| x == y8 | x == y9 | x == y10 | x == y11 | x == y12 | x == y13
    I used this code:
    Code:
    gen var2=1 if x == y`j' | x == y[`j'+1]
    But it did not give me the same results as before. How should I adjust the code?

  • #2
    You don't really need a loop.

    If these are numeric variables, you can simply use
    Code:
    gen byte var1 = inlist(x,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12,y13)
    If these are string variables, you are limited to nine comparisons, so you will need to break it up into two:
    Code:
    gen byte var1 = inlist(x,y1,y2,y3,y4,y5,y6,y7,y8,y9) | inlist(x,y10,y11,y12,y13)
    If you must use a loop (perhaps because this is one part of several other things you accomplish in the loop), you can do
    Code:
    gen byte var1 = 0
    
    forval j = 1/13 {
        replace var1 = 1 if x == y`j'
    }
    Last edited by Hemanshu Kumar; 03 Oct 2022, 04:37.

    Comment


    • #3
      Thank you Hemanshu, it worked very well.

      Comment

      Working...
      X