Announcement

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

  • First non zero observation in panel

    I need to create a variable equal to the first available value of a variable by country. However, the panel is unbalanced and for each country the first available observation of the variable is not the same.
    How can I do that?

  • #2
    So, if I understand what you want:

    Code:
    by country (time), sort: gen first_available_x = x[1]
    where x is the variable you want the first available value of.

    Hope this helps.

    Comment


    • #3
      However, that's based on what you wrote in the text. Your post's title says you want the first non-zero observation. In that case, it would be

      Code:
      gen byte zero_x = (x == 0)
      by country (zero_x time), sort: gen first_available_x = x[1]
      Because this code sorts the observations with x = 0 to the end of the country's list of values, this will work with just one exception. If all of a country's observations have x == 0, then this will set first_available_x to zero. If you would prefer first_available_x to be missing in this case, you can follow the above with:

      Code:
      replace first_available_x = . if first_available_x = 0

      Comment


      • #4
        sort countrycode year

        by countrycode: gen first= gdppcgrowth[_n] if gdppcgrowth[_n-1]==.

        list countrycode year gdppcgrowth first

        by countrycode:egen first2=mean(first)

        Comment


        • #5
          The code in your last post gives the average value of gdppcgrowth for those observations in which the preceding observation of gdppcgrowth is missing. Note, in particular, that this will always include the first observation of gdppcgrowth because gdppcgrowth[0] is always missing. But you said, at least in your title, that you wanted to exclude zero values.

          In any case, I no longer think I understand what you are looking for. If the code you posted does what you want, then great, you're done. If it isn't what you want, maybe you can clarify it by presenting a little bit of your data and showing what you want your new variable to look like.

          Comment


          • #6
            See also this FAQ for related technique http://www.stata.com/support/faqs/da...t-occurrences/

            Comment

            Working...
            X