Announcement

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

  • How to replace values (0 or missing) with maximum value in that year, for some variables?

    Hi all,

    For the panel data as below, I want to replace 0-or-missing values to the maximum value within the same year.
    I've tried loop with by option but it isn't very clear to me combining those with max function.

    year id var1 var2 var3 ...
    1999 14291 130 . 6
    1999 20186 0 705 0
    2000 14291 130 0 .
    2000 20186 0 819 .
    2001 14291 135 0 .
    2001 20186 0 769 .
    2002 14291 135 0 22
    2002 20186 0 783 0


    to...


    year id var1 var2 var3
    1999 14291 130 705 6
    1999 20186 130 705 6
    2000 14291 130 819 .
    2000 20186 130 819 .
    2001 14291 135 769 .
    2001 20186 135 769 .
    2002 14291 135 783 22
    2002 20186 135 783 22

  • #2
    Code:
    clear 
    input year id var1 var2 var3 
    1999 14291 130 . 6
    1999 20186 0 705 0
    2000 14291 130 0 .
    2000 20186 0 819 .
    2001 14291 135 0 .
    2001 20186 0 769 .
    2002 14291 135 0 22
    2002 20186 0 783 0
    end 
    
    forval j = 1/3 {
        egen max = max(var`j'), by(year)
        replace var`j' = max if inlist(var`j', 0, .)
        drop max 
    }
    
    list, sepby(year)
    
         +-----------------------------------+
         | year      id   var1   var2   var3 |
         |-----------------------------------|
      1. | 1999   14291    130    705      6 |
      2. | 1999   20186    130    705      6 |
         |-----------------------------------|
      3. | 2000   14291    130    819      . |
      4. | 2000   20186    130    819      . |
         |-----------------------------------|
      5. | 2001   14291    135    769      . |
      6. | 2001   20186    135    769      . |
         |-----------------------------------|
      7. | 2002   14291    135    783     22 |
      8. | 2002   20186    135    783     22 |
         +-----------------------------------+

    Comment


    • #3
      Thank you, Nick. I saved a lot of time.
      Your code works perfectly with the data.

      Comment

      Working...
      X