Announcement

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

  • Date Variable to show only year

    Hello,

    I was trying to make the date variable below into a yearly variable. I did the following: gen date2 = date(date, "Y")
    However it only showed missing values. Is this because the value is a string value? How would I go about it to get a yearly value for each value?

    Thanks!


    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str10 date float(pieati01dea661n date2)
    "2007-01-01"  93.03768 .
    "2008-01-01"  96.93327 .
    "2009-01-01"  93.65627 .
    "2010-01-01"   95.4023 .
    "2011-01-01"   99.3774 .
    "2012-01-01" 101.11848 .
    "2013-01-01" 100.90383 .
    "2014-01-01" 100.29961 .
    "2015-01-01"       100 .
    "2016-01-01"  99.16666 .
    "2017-01-01" 101.14167 .
    end

  • #2
    It being string is not the problem. date() is intended to take string input. The problem is using the wrong functions.

    Study the help for date() to see that it is for producing daily dates. That is more emphatic in the alternative name for the same function, daily().

    Either it does that successfully or it does that unsuccessfully, but it won't do what you want.

    So, you need something quite different. You can produce a daily date and then convert to years, or you can just read off what you need and ignore the rest.

    Either way, help datetime and help string functions explain all that you need to know to understand the code below.

    Code:
    clear
    
    input str10 date float(pieati01dea661n date2)
    "2007-01-01"  93.03768 .
    "2008-01-01"  96.93327 .
    "2009-01-01"  93.65627 .
    "2010-01-01"   95.4023 .
    "2011-01-01"   99.3774 .
    "2012-01-01" 101.11848 .
    "2013-01-01" 100.90383 .
    "2014-01-01" 100.29961 .
    "2015-01-01"       100 .
    "2016-01-01"  99.16666 .
    "2017-01-01" 101.14167 .
    end
    
    gen wanted1 = year(daily(date, "YMD"))
    
    gen wanted2 = real(substr(date, 1, 4))
    
    list date wanted1 wanted2
    
         +--------------------------------+
         |       date   wanted1   wanted2 |
         |--------------------------------|
      1. | 2007-01-01      2007      2007 |
      2. | 2008-01-01      2008      2008 |
      3. | 2009-01-01      2009      2009 |
      4. | 2010-01-01      2010      2010 |
      5. | 2011-01-01      2011      2011 |
         |--------------------------------|
      6. | 2012-01-01      2012      2012 |
      7. | 2013-01-01      2013      2013 |
      8. | 2014-01-01      2014      2014 |
      9. | 2015-01-01      2015      2015 |
     10. | 2016-01-01      2016      2016 |
         |--------------------------------|
     11. | 2017-01-01      2017      2017 |
         +--------------------------------+

    Comment


    • #3
      Thanks Cox

      Comment

      Working...
      X