Announcement

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

  • Replace Command under Certain Conditions

    Dear Stata experts,

    I'm trying to get my head around how to best perform this operation. Bellow is a toy example of my dataset that should hopefully describe the problem I'm facing.


    clear
    input id wave oldsex newsex
    100 1 1 .
    100 2 2 .
    101 1 1 .
    101 2 2 .
    101 3 2 .
    102 1 1 .
    102 2 2 .
    103 1 2 .
    103 2 1 .
    103 3 2 .
    end



    For my analysis I try to replace the values of a new variable (newsex) with the values from an old variable (oldsex) but under certain conditions (wave==2).

    Given the toy data above, my aim is to replace the value of newsex per ID and for all waves with the value of wave 2. For example, ID 103 has the values 2, 1, 2 but given the fact that I'm purely interested in a parent's sex at time point 2 (wave==2) I'd like to change the values of newsex to 1, 1, 1.

    It might be a very simple question for you, bu I'm stuck and whatever I try do not find a way around this issue.

    I would really appreciate your help!

    Thank you in advance,
    Jonas


  • #2
    Thanks for the clear data example and question.

    Code:
    clear
    input id wave oldsex newsex
    100 1 1 .
    100 2 2 .
    101 1 1 .
    101 2 2 .
    101 3 2 .
    102 1 1 .
    102 2 2 .
    103 1 2 .
    103 2 1 .
    103 3 2 .
    end
    
    egen wanted = total(cond(wave == 2, oldsex, .)), by(id) 
    
    list , sepby(id) 
    
         +---------------------------------------+
         |  id   wave   oldsex   newsex   wanted |
         |---------------------------------------|
      1. | 100      1        1        .        2 |
      2. | 100      2        2        .        2 |
         |---------------------------------------|
      3. | 101      1        1        .        2 |
      4. | 101      2        2        .        2 |
      5. | 101      3        2        .        2 |
         |---------------------------------------|
      6. | 102      1        1        .        2 |
      7. | 102      2        2        .        2 |
         |---------------------------------------|
      8. | 103      1        2        .        1 |
      9. | 103      2        1        .        1 |
     10. | 103      3        2        .        1 |
         +---------------------------------------+
    For a review of technique in this territory, see https://www.stata-journal.com/sjpdf....iclenum=dm0055 especially sections 9 and 10.

    Comment


    • #3
      Dear Nick,

      thank you very much for your help. You saved my day.

      Again, thanks a million!

      Comment

      Working...
      X