Announcement

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

  • Numeric counter of dates between min and max

    Should be easy, but I don't get it (I hate dates). I have a monthly %tm variable and want a variable t = 1 for the lowest month in the data, t = 2 for the second-lowest etc. Can someone illuminate me please?

  • #2
    Dates in Stata are just integers The rest is human conventions that people mostly learn by age 11 or so.

    No data example here or explanation of your data structure. (I hate questions that are unclear...)

    Perhaps you want some equivalent of

    Code:
    bysort id (mdate) : gen counter = _n
    or

    Code:
    bysort id (mdate) : gen COUNTER = mdate - mdate[1] + 1
    noting that

    1. If the date are not panel data, then

    Code:
    sort mdate 
    gen counter = ... 
    gen COUNTER = .
    will suffice

    2. If there are gaps in the data the two answers will differ.

    Comment


    • #3
      Since the question is unclear, there are even further options for (mis)interpreting what is wanted.

      Perhaps you want
      Code:
      summarize mdate, meanonly
      generate t = mdate-r(min)+1
      where t=1 is the lowest mdate regardless of any possible panel structure, and where if there is a gap in the mdate values there will be a corresponding gap in the t values, as befits a "time" variable.

      If this is indeed what you want, another interpretation is "you don't need this variable, you can obtain your objective using your monthly variable directly." Put another way, it's not obvious what benefit subtracting the same constant from every date will yield.

      Comment


      • #4
        Thanks a lot! Indeed what Nick Cox suggest is what I was looking for.

        And yes, caveat 2 might be an issue here as the panel is unbalanced. Is there a way to address this? Below is a data example, for id = 2 there is no observation in 2009m11. I would like the counter to skip the number 2 in that case as in data below.

        Code:
        input id mdate counter
        1 2009m10 1
        1 2009m11 2
        1 2009m12 3
        2 2009m10 1
        2 2009m12 3
        2 2010m01 4
        end

        Comment


        • #5
          The second line of code in #2 does this. Did you try it?

          Comment


          • #6
            Ah, I misunderstood that both do the same and just used the first one. Thank you

            Comment


            • #7
              Nooo, they aren't the same if you have gaps.

              Comment

              Working...
              X