Announcement

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

  • Adding a character at a certain place within a string variable

    Hi everyone,

    I've got a string variable ("ID") which contains a patient code. This code ist composed of the patients' 3rd letter of his/her first name, the 3rd letter of his/her last name, the date of his/her birthday and a clinic identifier.

    For example: Jane Meyer, born on the 11th of November, patient in the clinic with the number 22 would have the following patient code: NY1122.
    If Jane Meyer would have been born on the 8th of November, her code would be: NY0822.
    However, for some patients it has been forgotten to include the "0" when the day of the birthday was single-digit. So sometimes it's: NY822.

    I want to add the character "0" for these cases. So I am looking for something that says: add a 0 on the third place of the string label if the label is 5 characters long.

    I am quite at loss how to do this and would really appreciate your help!

    Best
    Katja

  • #2
    Code:
    help string functions
    is your friend here and indeed https://journals.sagepub.com/doi/pdf...867X1101100308 may help. (Note: StataCorp has changed the preferred function names in a few cases since that paper, but the names discussed in that paper should all work.)


    Code:
    replace ID = substr(ID, 1, 2) + "0" + substr(ID, 3, .) if strlen(ID) == 5

    Comment


    • #3
      Thank you very much!! This is the solution! :-)

      Comment


      • #4
        Hi there,

        I am trying to do a similar thing but am getting an invalid syntax error, can anyone tell me why?

        Code:
        replace atc_code = substr(atc_code, 1) + "0" + substr(atc_code, 2, .) if strlen(atc_code) == 5
        I've checked the variable is a string.. I note it works if I insert the zero in the 3rd position (per below) but I need it to be in the second.

        Code:
        replace atc_code = substr(atc_code, 1, 2) + "0" + substr(atc_code, 3, .) if strlen(atc_code) == 5
        Many thanks,
        Hannah

        EDIT: Apologies - checked the help for substr - code should be

        Code:
        replace atc_code = substr(atc_code, 1, 1) + "0" + substr(atc_code, 2, .) if strlen(atc_code) == 5
        Last edited by Hannah Beilby; 19 May 2024, 17:47.

        Comment

        Working...
        X