Announcement

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

  • Extracting first four digits from a string (long)

    I would like to extrapolate the first 4 digits from a string variable, which includes the date (19260615) YYYYMMDD.

    generate issue_year = substr(issue_date,1,4)

    This gives me: type mismatch

    Can you kindly help me?

    Thanks!

  • #2
    You probably have a numeric date variable that you consider to be a string. Try

    Code:
    gen issue_year= year(issue_date)
    If this does not help, present a data example using the dataex command.

    Code:
    dataex issue_date in 1/5

    Comment


    • #3
      Thanks Andrew.

      Unfortunately, the code that you suggested does not work.
      gen issue_year= year(issue_date)



      Thus, here is what you asked me:

      . dataex issue_date in 1/5

      ----------------------- copy starting from the next line -----------------------
      Code:
      * Example generated by -dataex-. To install: ssc install dataex
      clear
      input long issue_date
      19260126
      19260126
      19260126
      19260126
      19260126
      end
      ------------------ copy up to and including the previous line ------------------


      I would appreciate if any of you could help me with this query.

      Thanks!

      Comment


      • #4
        Code:
        * Example generated by -dataex-. To install: ssc install dataex
        clear
        input long issue_date
        19260126
        19260126
        19260126
        19260126
        19260126
        end
        
        
        gen date= daily(string(issue_date, "%9.0f"), "YMD")
        format date %td
        gen year= year(date)
        Res.:

        Code:
        . l
        
             +-----------------------------+
             | issue_~e        date   year |
             |-----------------------------|
          1. | 19260126   26jan1926   1926 |
          2. | 19260126   26jan1926   1926 |
          3. | 19260126   26jan1926   1926 |
          4. | 19260126   26jan1926   1926 |
          5. | 19260126   26jan1926   1926 |
             +-----------------------------+
        Note that

        Code:
        gen year= real(substr(string(issue_date, "%9.0f"), 1, 4))
        or

        Code:
        gen year= int(issue_date/1e+4)

        follows your initial idea, but here I generate a Stata date variable that you can use generally.
        Last edited by Andrew Musau; 18 Dec 2023, 04:08.

        Comment


        • #5
          Thanks a lot!

          Comment

          Working...
          X