Announcement

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

  • Generate new variable if meets conditions from 3 or 4 other variables

    I have 4 binary variables (0/1) and trying to create a newvar=1 if any 3 of those 4 variables ==1 and 0 if not.
    I can write it with a lot of if statements, but can't figure an easier way which I am sure exists

    Thanks

  • #2
    Assuming that you do not have any missing values, how about something like this untested code:

    Code:
    tempvar flag
    gen flag=(v1+v2+v3+v4)
    generate newvar=0
    replace newvar=1 if `flag'==1

    Comment


    • #3
      Here's a method that should work even if you have missing values.

      Code:
      * Generate some data to illustrate
      clear *
      input byte(v1 v2 v3 v4)
      . . . .
      0 0 0 0
      1 1 1 1
      end
      fillin v1 v2 v3 v4
      drop _fillin
      
      egen byte rowsum = rowtotal(v1-v4)
      generate byte flag = rowsum > 2
      list if flag==1
      Output from the list command:

      Code:
      . list if flag==1
      
           +-----------------------------------+
           | v1   v2   v3   v4   rowsum   flag |
           |-----------------------------------|
       14. |  0    1    1    1        3      1 |
       32. |  1    0    1    1        3      1 |
       38. |  1    1    0    1        3      1 |
       40. |  1    1    1    0        3      1 |
       41. |  1    1    1    1        4      1 |
           |-----------------------------------|
       42. |  1    1    1    .        3      1 |
       44. |  1    1    .    1        3      1 |
       50. |  1    .    1    1        3      1 |
       68. |  .    1    1    1        3      1 |
           +-----------------------------------+

      --
      Bruce Weaver
      Email: [email protected]
      Version: Stata/MP 18.5 (Windows)

      Comment


      • #4
        thanks so much - worked beautifully!

        Comment

        Working...
        X