Search code examples
datestata

Create calendar year variable from daily date


I have a Stata elapsed date variable (excerpt below) for each patient patid. But I believe I need to generate a new variable if I were to make use of only the year element within that date, that is, not just change the display format.

clear
input long patid float date
1015 18766
1018 13135
1020 13325
1025 14384
1029 14514
1050 13501
1070 14523
1071 14878
1090 14701
1092 14159
end
format %td date

How do I generate a year variable for all dates within the same year? That is all days from 1st January to 31st December of the same year?


Solution

  • That calls for just the function year(), which together with similar stuff is prominently documented at help datetime.

    clear
    input long patid float date
    1015 18766
    1018 13135
    1020 13325
    1025 14384
    1029 14514
    1050 13501
    1070 14523
    1071 14878
    1090 14701
    1092 14159
    end
    format %td date
    
    gen year = year(date) 
    
    list 
    
         +--------------------------+
         | patid        date   year |
         |--------------------------|
      1. |  1015   19may2011   2011 |
      2. |  1018   18dec1995   1995 |
      3. |  1020   25jun1996   1996 |
      4. |  1025   20may1999   1999 |
      5. |  1029   27sep1999   1999 |
         |--------------------------|
      6. |  1050   18dec1996   1996 |
      7. |  1070   06oct1999   1999 |
      8. |  1071   25sep2000   2000 |
      9. |  1090   01apr2000   2000 |
     10. |  1092   07oct1998   1998 |
         +--------------------------+