Announcement

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

  • Multiple replacements with multiple rules

    For a sample data generated by the code below, I want to replace y1 to y10 variables with y_norm y_bad and y_good such that y_norm is repeated r_norm times, y_bad is repeated r_bad times and y_good is repeated r_good times . Instead of directly replacing, generating these variables with this rule is also fine.
    For instance, for first row: y1, y2, y3 should take the value of y_norm because r_norm=3, then the remaining y4 to y10 variables should take the value of y_good because r_good = 7.
    Similarly, for second row: variables y1 to y4 takes the values of y_norm (since r_norm=4) , y5 takes the value of r_bad (since r_bad=1), and y6 to y10 takes the value of y_good (since r_good=5).
    How can this be done with STATA?

    The code for sample data:


    Code:
    clear all
    set obs 15
    gen id = _n
    
    set seed 1198810031
    gen y_norm = runiform(500, 12000)
    gen y_bad = y_norm/3 * runiform(0,1)
    gen y_good = y_norm*4
    
    gen r_norm = runiformint(0,5)
    
    gen r_bad = int(3-r_norm)
    replace r_bad = r_bad*(-1) if r_bad <0
    gen r_good = 10-r_norm - r_bad
    
    forvalues i = 1/10 {
        gen y`i' = .
    }

  • #2
    This is a great example of something that will be crazy-makingly difficult in wide layout, but is quite simple in long layout. -reshape- to the rescue!
    Code:
    assert r_norm + r_bad + r_good == 10
    
    reshape long y, i(id) j(varnum)
    by id (varnum), sort: replace y = y_norm if _n <= r_norm
    by id (varnum): replace y = y_bad if inrange(_n, r_norm+1, r_norm+r_bad)
    by id (varnum): replace y = y_good if inrange(_n, r_norm+r_bad+1, _N)
    reshape wide
    By the way, I don't know what you are going to do with y1 through y10 once you have them, but there is a very high probability that it, too, will be easier with long layout. So consider skipping the last -reshape wide- and sticking with long layout all the way.

    Comment


    • #3
      Thank you Clyde. This is incredibly helpful.

      Comment

      Working...
      X