Announcement

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

  • Manipulating panel data based on previous time values

    Hi,

    I am working with a district-year panel data set in which there are 10 years. I am interested in the value of a count variable "X" across the years that ranges from 1-9. I want to code it such that that the value of X can never decrease. For example, here is the original data:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input double uniqueid float(year X)
    1001 2000 0
    1001 2001 1
    1001 2002 0
    1001 2003 1
    1001 2004 2
    1001 2005 1
    1001 2006 2
    1001 2007 2
    1001 2008 2
    1001 2009 4
    1001 2010 3
    end
    where the goal would be to have:

    Code:
    input double uniqueid float(year X)
    1001 2000 0
    1001 2001 1
    1001 2002 1
    1001 2003 1
    1001 2004 2
    1001 2005 2
    1001 2006 2
    1001 2007 2
    1001 2008 2
    1001 2009 4
    1001 2010 3
    end
    Would the proper way to approach this be to replace the X value with the preceding if the current is less than the preceding?

    Thank you.














  • #2
    I think there is an error in your example. Shouldn't the value of x in the last observation shown in the second -dataex- be 4, not 3? As shown, x decreases from 2009 to 2010.

    If I have that right, then the following does what you want:

    Code:
    gen x_wanted = X
    by uniqueid (year), sort: replace x_wanted = max(x_wanted, x_wanted[_n-1])

    Comment


    • #3
      https://www.stata.com/support/faqs/d...m-of-sequence/ gave a longer discussion of this problem, including a one-line solution.

      Comment


      • #4
        Great, thank you for the help.

        Comment

        Working...
        X