Announcement

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

  • Creating variable based on conditions of two variables using matrix

    Dear everyone

    I'm trying to create a variable based on matrix conditions of two other variable.

    I acknowledge that the the screenshoot is not the best way to show you the data but this is my starting point:
    On stata, I have the variable a and b and I need to create the variable c based on the values of a and b (below the conditions)

    For instance if 0<=a<0.1 and 0<=b<10, then c = 0.005

    Do you have any advice on how to approach it that is best time-efficient (i.e. without manually including all conditions with if/or commands)?

    Click image for larger version

Name:	matrix.png
Views:	1
Size:	17.9 KB
ID:	1640876

  • #2
    Here is an example. The trick is that we create variables (atemp and btemp) that contain the rownumber and columnnumber for the matrix. You still have to use some if conditions, but only for both variables in isolation and not the combination. So it saves quite a bit.

    Code:
    clear
    set obs 1000
    gen a = runiform()
    gen b = runiform()
    
    matrix goal = 8, 9, 10, 11 \ ///
                  7, 8,  9, 10 \ ///
                  6, 7,  8,  9 \ ///
                  5, 6,  7,  8
                
    generate atemp = 1 if a < .25
    replace  atemp = 2 if a >=.25 & a < .50
    replace  atemp = 3 if a >=.50 & a < .75
    replace  atemp = 4 if a >=.75 & a < .
    
    
    generate btemp = 1 if b < .25
    replace  btemp = 2 if b >=.25 & b < .50
    replace  btemp = 3 if b >=.50 & b < .75
    replace  btemp = 4 if b >=.75 & b < .
    
    gen wanted = goal[atemp, btemp]
    Last edited by Maarten Buis; 14 Dec 2021, 11:29.
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Thank you Maarten Buis !

      I wil implement it in my analisis

      Comment

      Working...
      X