Announcement

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

  • Local macro and foreach loop

    Hi Statalist,

    I need to generate a new variable == 1 if any of the values in a sequence of 20 variables (for any individual observation) is between 1 and 4. Because there are so many variables I've been trying to do this with a foreach loop and local macro, but unfortunately the number that's "counting up" is in the middle of the variable name, not the end. Is there a concise way for me to do this (i.e., without listing out all the variable names)? Something like RX*A_wave1?

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input byte(rx1a_wave1 rx2a_wave1 rx3a_wave1 rx4a_wave1 rx5a_wave1 rx6a_wave1) long id
    3 2 4 1 2 3 523425
    3 2 4 1 2 3 523418
    4 3 . 6 7 2 523411
    3 2 3 1 1 1 523404
    4 3 2 0 0 0 523397
    5 2 4 5 2 1 523390
    4 5 6 7 5 3 523383
    6 1 6 7 3 3 523376
    1 2 3 4 1 1 523369
    4 3 4 6 7 2 523362
    3 2 3 1 1 1 523355
    4 3 2 0 0 0 523348
    3 2 3 1 1 1 523341
    7 7 5 0 3 0 523334
    4 7 1 7 7 1 523327
    5 3 4 5 3 1 523320
    3 2 3 1 1 1 523313
    1 7 5 0 0 0 523306
    4 1 1 1 1 1 523299
    5 . 4 5 2 1 523292
    4 5 6 7 5 3 523285
    6 1 6 7 5 3 523278
    3 2 3 . 1 1 523271
    4 5 6 7 5 3 523264
    end

  • #2
    Code:
    gen wanted = 0 
    
    foreach v of var rx*a_wave1 { 
        replace wanted = 1 if inrange(`v', 1, 4)
    }

    Comment

    Working...
    X