Announcement

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

  • creating a variable from multiple values in a condition

    Hello everyone, I am new here. I intend to create a new variable (say X) conditioned on the values of four other binary variables (A, B, C, D).
    X will range from1 to 16, as in the above table. For instance X = 1 if A=1, B=1, C=1 and D=1 simultaneously. I would appreciate it if someone could tell me how to do it.
    With sincere appreciation
    A B C D x
    1 1 1 1 1
    0 1 1 1 2
    1 0 1 1 3
    1 1 0 1 4
    1 1 1 0 5
    0 0 1 1 6
    0 1 0 1 7
    0 1 1 0 8
    1 0 0 1 9
    1 0 1 0 10
    1 1 0 0 11
    1 0 0 0 12
    0 1 0 0 13
    0 0 1 0 14
    0 0 0 1 15
    0 0 0 0 16

  • #2
    Code:
    egen wanted= group(A B C D)
    will map a combination to a value between 1-16 (not necessarily that 1 1 1 1 will be mapped to 1). The same combinations will be mapped to the same number.

    Comment


    • #3
      If you actually want the exact results shown in post #1 the following will do it.
      Code:
      // read your example data
      * Example generated by -dataex-. For more info, type help dataex
      clear
      input byte(a b c d x)
      1 1 1 1  1
      0 1 1 1  2
      1 0 1 1  3
      1 1 0 1  4
      1 1 1 0  5
      0 0 1 1  6
      0 1 0 1  7
      0 1 1 0  8
      1 0 0 1  9
      1 0 1 0 10
      1 1 0 0 11
      1 0 0 0 12
      0 1 0 0 13
      0 0 1 0 14
      0 0 0 1 15
      0 0 0 0 16
      end
      
      // generate want to equal your x
      generate want1 = 1*a + 2*b + 4*c + 8*d
      recode want1 (15=1) (14=2) (13=3) (11=4) (7=5)  (12=6) (10=7) (6=8) ///
                   (9=9)  (5=10) (3=11) (1=12) (2=13) (4=14) (8=15) (0=16), generate(want)
      list, clean
      Code:
      . list, clean
      
             a   b   c   d    x   want1   want  
        1.   1   1   1   1    1      15      1  
        2.   0   1   1   1    2      14      2  
        3.   1   0   1   1    3      13      3  
        4.   1   1   0   1    4      11      4  
        5.   1   1   1   0    5       7      5  
        6.   0   0   1   1    6      12      6  
        7.   0   1   0   1    7      10      7  
        8.   0   1   1   0    8       6      8  
        9.   1   0   0   1    9       9      9  
       10.   1   0   1   0   10       5     10  
       11.   1   1   0   0   11       3     11  
       12.   1   0   0   0   12       1     12  
       13.   0   1   0   0   13       2     13  
       14.   0   0   1   0   14       4     14  
       15.   0   0   0   1   15       8     15  
       16.   0   0   0   0   16       0     16

      Comment

      Working...
      X