Announcement

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

  • Subtract a part of a string depending on the number of digits

    Hello,

    I have a string variable, let's called it "string". Sometimes it has 10 digits, and some times 9. I would like to obtain create a new variable which takes the first 8 digit if it has 10 digits, and to takes the first 7 digit if it has 9 digit.

    I know how to do it considering just one part:

    Code:
    gen wanted = substr(string, 1, 8)
    However, I have not found the way of doing both parts at the same time. Any ideas?

  • #2
    Code:
    gen wanted = string(trunc(real(string)/100), "%18.0g")
    Last edited by daniel klein; 17 Oct 2023, 08:35. Reason: added display format to string(); should be strtoreal() in modern Stata

    Comment


    • #3
      See

      Code:
      help length()
      and

      Code:
      help cond()
      If it is a binary condition, i.e., either a value is 10 digits long or 9 digits long, then you can have

      Code:
      gen wanted= cond(length(stringvar)==10, substr(stringvar, 1, 8), substr(stringvar, 1, 7))
      If there are more possibilities, specify multiple conditions.

      Note: Crossed with #2.

      Comment


      • #4
        Andrew Musau Thanks a lot Andrew! It works perfectly. I did not know the existence of length() command.

        daniel klein Thanks a lot for your answer! I also tried your solution and it also works! However for some numbers it gives me the result in scientific notation.


        Comment


        • #5
          Originally posted by Diego Malo View Post
          daniel klein Thanks a lot for your answer! I also tried your solution and it also works! However for some numbers it gives me the result in scientific notation.
          That should have been fixed with the edited post, including the "%18.0g" display format.

          Comment

          Working...
          X