Announcement

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

  • How to assign the same value every 3 observations

    Suppose I have a panel data with 2 firms and each firm has 6 observations of variable called y

    id y
    1 1
    1 2
    1 3
    1 4
    1 5
    1 6
    2 6
    2 5
    2 4
    2 3
    2 2
    2 1

    I would like to transform the variables as follows (assign the same y every three observations based on the first observation of y at the 1st, 4th observation etc)

    id y
    1 1
    1 1
    1 1
    1 4
    1 4
    1 4
    2 6
    2 6
    2 6
    2 3
    2 3
    2 3

    I know how to do it using other software using a for loop but couldn't figure out a way to do it in STATA, could someone help me with it? Thanks a lot!!

  • #2
    Hi Li Ma,

    Try the following:

    Code:
    gen n = _n +2
    gen div = n/3
    gen mark = 1 if div == floor(div)
    drop n div
    
    replace y = y[_n-1] if mark==.

    Comment


    • #3
      Originally posted by Igor Paploski View Post
      Hi Li Ma,

      Try the following:

      Code:
      gen n = _n +2
      gen div = n/3
      gen mark = 1 if div == floor(div)
      drop n div
      
      replace y = y[_n-1] if mark==.
      It works very well, Thank you so much, Igor!

      Comment


      • #4
        Consider also this

        Code:
        clear 
        
        input id y
        1 1
        1 2
        1 3
        1 4
        1 5
        1 6
        2 6
        2 5
        2 4
        2 3
        2 2
        2 1
        end 
        
        gen wanted = y if mod(_n, 3) == 1
        replace wanted = wanted[_n-1] if missing(wanted) 
        
        list, sep(3)
        
        
             +-----------------+
             | id   y   wanted |
             |-----------------|
          1. |  1   1        1 |
          2. |  1   2        1 |
          3. |  1   3        1 |
             |-----------------|
          4. |  1   4        4 |
          5. |  1   5        4 |
          6. |  1   6        4 |
             |-----------------|
          7. |  2   6        6 |
          8. |  2   5        6 |
          9. |  2   4        6 |
             |-----------------|
         10. |  2   3        3 |
         11. |  2   2        3 |
         12. |  2   1        3 |
             +-----------------+

        Comment

        Working...
        X