Announcement

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

  • How to Replace the Missing Values with the Preceding Value within Group in Stata?

    I have a dataset like this,
    clear
    input byte (id state)
    1 0
    1 .
    1 1
    2 0
    2 .
    2 1
    3 0
    3 .
    3 1
    3 .
    3 .
    3 .
    3 0
    3 .
    4 0
    4 .
    4 .
    4 .
    4 .
    4 .
    4 .
    4 1
    end

    I want to replace the missing values with the preceding value within id.
    For example, when id==3, the filled data looks like as follows,
    3 0
    3 0
    3 1
    3 1
    3 1
    3 1
    3 0
    3 0
    Can someone help me with Stata code?
    Thank you!

  • #2
    Jason:
    being aware of the methodological risks that the LOCF approach comes with, you may want to try:
    Code:
    . bysort id: replace state=state[_n-1] if state[_n-1]!=. & state[_n]==.
    (13 real changes made)
    
    . list
    
         +------------+
         | id   state |
         |------------|
      1. |  1       0 |
      2. |  1       0 |
      3. |  1       1 |
      4. |  2       0 |
      5. |  2       0 |
         |------------|
      6. |  2       1 |
      7. |  3       0 |
      8. |  3       0 |
      9. |  3       1 |
     10. |  3       1 |
         |------------|
     11. |  3       1 |
     12. |  3       1 |
     13. |  3       0 |
     14. |  3       0 |
     15. |  4       0 |
         |------------|
     16. |  4       0 |
     17. |  4       0 |
     18. |  4       0 |
     19. |  4       0 |
     20. |  4       0 |
         |------------|
     21. |  4       0 |
     22. |  4       1 |
         +------------+
    
    .
    Kind regards,
    Carlo
    (Stata 19.0)

    Comment


    • #3
      Thank you!

      Comment


      • #4
        This is also an FAQ: https://www.stata.com/support/faqs/d...issing-values/

        Comment

        Working...
        X