Announcement

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

  • Generating daily dates observations by ID

    Hi everyone,
    I am stuck and would really appreciate if someone can help me out here. I have a dataset where two variables id2 and year identifies each row uniquely. I would like to create a date variable for each id-year case that populates daily date observations. For instance, I have the dataset which looks like this


    id2 year
    115511 2014
    115511 2015
    115511 2016
    115512 2014
    115512 2017
    115512 2013
    115521 2014
    115521 2015


    and I would like to make it look like this, where the dots (.) show continuation of the date variable until 31-Dec



    id2 year Date
    115511 2014 1-Jan-14
    115511 2014 2-Jan-14
    115511 2014 .
    115511 2014 .
    115511 2014 31-Dec-14
    115511 2015 1-Jan-15
    115511 2015 2-Jan-15
    115511 2015 .
    115511 2015 .
    115511 2015 31-Dec-15


    I could probably do this in excel but the dataset size limits me to open this up in Excel. Any help is much appreciated.

  • #2
    Code:
    expand 400
    bysort id2 year: gen double date = mdy(1,1,year) + _n - 1
    drop if yofd(date)>year
    format %td date

    Comment


    • #3
      @Øyvind Snilsberg's code is manifestly a quick if dirty way to get Stata sort out leap years. It will be correct and quicker at that than any programmer will be.

      Alternatively,

      Code:
      clear 
      input year
      2015
      2016 
      2017 
      2000
      2100 
      end 
      
      gen toexpand = 365 + ((mod(year, 4) == 0 & mod(year, 100) != 0) | mod(year, 400) ==  0)  
      
      list 
      
           +-----------------+
           | year   toexpand |
           |-----------------|
        1. | 2015        365 |
        2. | 2016        366 |
        3. | 2017        365 |
        4. | 2000        366 |
        5. | 2100        365 |
           +-----------------+
      
      expand toexpand

      There is documentation on such a direct solution. See https://www.stata.com/support/faqs/d...ar-indicators/

      That really isn't a frequently asked or answered question that I know. Rather, once I needed to work it out, and when I had done so I knew that an answer would be safer on StataCorp's website than on any computer I had, and the company was happy to post it. The number of files or useful things lost because of computer changes or crashes or because I can't remember how I saved some stuff doesn't bear thinking about.

      Comment


      • #4
        This was very useful. Thank you both,

        Comment

        Working...
        X