Announcement

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

  • Retaining last two digits only of a numeric variable

    This is probably dead easy but I am stuck. I have a variable yearmonth which is in the format 901 for January 2009, and 1210 for October 2012. I am trying to separate out a year and a month variable. I would like the years as 2009 etc, and the months just 1 to 12. Any ideas?

    thanks all!


  • #2
    Oops, that is silly and works only if we had months 0-9... I need to go now, so I won't be able to give a more sensible solution
    Code:
    gen year = floor(yearmonth/10)
    gen month = mod(yearmonth,10)
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Yep, that doesn't quite do the trick. anyone else got an idea?

      Comment


      • #4
        Modulo 100, not 10? add 2000 for year.

        Comment


        • #5
          While there are plenty of smart numeric ways to do this, I find it easier to use simple string methods

          Code:
          set obs 2
          gen date = 901
          replace date = 1210 in 2
          
          gen dateString = string(date)
          gen month = substr(dateString, -2, 2)
          gen year = substr(dateString, 1, length(dateString)-2)
          destring month year, replace
          The first substring extracts the last two digits, the second everything but the last two.

          Comment


          • #6
            a nice one, jesse, that worked. thanks very much

            Comment


            • #7
              Completing the sequence started with #2 and #4:

              Code:
              .  clear 
              
              .  set obs 2
              number of observations (_N) was 0, now 2
              
              .  gen have = cond(_n == 1, 901, 1210) 
              
              .  
              .  gen want = ym(2000 + floor(have/100), mod(have, 100)) 
              
              .  format want %tm 
              
              .  
              .  list 
              
                   +----------------+
                   | have      want |
                   |----------------|
                1. |  901    2009m1 |
                2. | 1210   2012m10 |
                   +----------------+

              Comment

              Working...
              X