Announcement

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

  • String - Abbreviating first letter of first name, but leaving surname intact

    Hi all. How does one go about transforming the string variable name to name2 as seen below:
    name name2
    Stephen Curry S. Curry
    Kevin Durant K. Durant
    J.J. Reddick J.J. Reddick
    name is mostly Firstname Lastname as seen, however instances of double initials a la J.J. Reddick and D.J. Augustin do pop up. When looking I have come across ustr and usub but have not been able to get these to work.

    Many thanks to all who respond.

  • #2
    This code works for the example you gave. I don't know what all complications exist in your overall data, so this may or may not suffice:
    Code:
    split name
    replace name1 = substr(name1,1,1) + "." if !strpos(name1,".")
    gen name_wanted = name1 + " " + name2
    drop name?

    Comment


    • #3
      Thank you. split is a command I will definitely be remembering. I was struggling with separating the first and last names.

      Also, what does the ! in !strpos do to the command?

      Comment


      • #4
        The ! is the NOT operator. If there is a period in name1, strpos will return a positive value, which in logical terms, evaluates to TRUE, and the ! changes that to FALSE (and vice-versa if there is no period in name1).

        Comment


        • #5
          So it does the counter of the original command. Many thanks. Have a nice day.

          Comment


          • #6
            For Stata users comfortable with regular expression matching syntax, this can be done using a single match-and-replace.
            Code:
            . generate name2 = ustrregexrf(name, "^([A-Z])[^ \.]* ", "$1. ")
            
            . list, clean
            
                            name          name2  
              1.   Stephen Curry       S. Curry  
              2.    Kevin Durant      K. Durant  
              3.    J.J. Reddick   J.J. Reddick  
              4.     W. Lisowski    W. Lisowski

            Comment

            Working...
            X