Announcement

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

  • Removing first numbers on a numeric variable

    Hi!

    I have been looking around for a simple way to remove part of my numeric variable, but didn't find an answer. Could anyone help, please?
    Current variable (yearmonth -numeric) --> 200101 (all starting with 200)
    What I want to keep ---> 101
    So I want to remove the first bit, 200, but maintain it as a number and ideally the name as well.
    Thank!!

  • #2
    if all values are similar to the one you show you can use the following:
    Code:
    gen newvar = real(substr(string(200101),4,3)
    replace "newvar" with your choice

    replace "200101" with the variable name in your data set

    Comment


    • #3
      Code:
      generate newvar = yearmonth-200000
      Best
      Daniel

      Comment


      • #4
        Of course, it makes total sense what you mention, Daniel!
        I will also try that one, Rich
        Thanks for helping me out!
        Accidentally I got to something like:
        replace yearmonth = mod( yearmonth, 1000)
        It does seem to work!

        Comment


        • #5
          Although people answered your question as you asked, if your variable contains values like 200101, 200102, 200112, 200201, 200202, ... then you have solved one problem only to create another as values like 101, 102, ..., 112, 201, 202,.... are just as awkward. This problem is discussed in a Tip to appear in Stata Journal 18(3). Meanwhile the best way to get a monthly date out of your date is something like this

          Code:
           clear 
           input yearmonth 
           200101 
           200102
           200112 
           200201
           200202
           end 
           
           gen mdate = ym(floor(yearmonth/100), mod(yearmonth, 100)) 
           
           format mdate %tm 
           
           list
           
                +--------------------+
               | yearmo~h     mdate |
               |--------------------|
            1. |   200101    2001m1 |
            2. |   200102    2001m2 |
            3. |   200112   2001m12 |
            4. |   200201    2002m1 |
            5. |   200202    2002m2 |
               +--------------------+
          This also works with numdate (SSC): (see e.g. https://www.statalist.org/forums/for...date-variables)

          Code:
          numdate monthly mdate2 = yearmonth, pattern(YM)


          Comment

          Working...
          X