Announcement

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

  • Concatenate names using loops and egen

    Hi All,

    Please can someone help me with the stata codes that will concatenate the names provided below.
    I have over 500 names and want to make use of the loops and egen commands.

    My data is as shown below and my expected results is beneath the data

    Thanks for your assistance

    Data:

    first_name_1 first_name_2 last_name_1 last_name_2
    Daniel Joseph Kanyam Mensah
    Michael John Kombat Smith

    Expected Result:

    fullname1 fullname2
    Daniel Kanyam Joseph Mensah
    Michael Kombat John Smith


  • #2
    So something like this:

    Code:
    forvalues j = 1/500 {
    egen full_name_`j' = concat(first_name_`j' last_name_`j')
    }
    That said, a data set with 500 sets of names in wide layout is likely to be unwieldy for any purpose you might put it to. Consider switching over to the long layout, which then enables you to do this with a single command, and probably leaves you with much more usable data anyhow. (Most things in Stata works better in long layout than wide.)

    Code:
    gen obs_no = _n
    reshape long first_name_ last_name_, i(obs_no) j(name_no)
    egen full_name = concat(first_name_ last_name_)
    Last edited by Clyde Schechter; 04 Mar 2015, 10:35.

    Comment


    • #3
      Many thanks Clyde.I really appreciate your quick response

      Comment


      • #4

        forvalues j = 1/500 { egen full_name_`j' = concat(first_name_`j' last_name_`j') } Hi Clyde, The code worked perfectly.Thanks once again But what if the names have leading zeros like first_name_01 first_name_02 last_name_01 last name_02 Thanks Dan

        Comment


        • #5
          Looping over 01, 02, etc. is discussed within http://www.stata-journal.com/sjpdf.h...iclenum=pr0051

          Comment


          • #6
            Many thanks Cox.I used the commands in your paper and i don't get any output and i don't get errors either.

            Below are my commands


            forvalues j = 1/25 {
            local i : di %02.0f `j'
            display "`j'"
            use data`j'
            egen full_name_`j' = concat(name_`j' last_name_`j'),p(" ")

            }

            Thanks

            Comment


            • #7
              Daniel,

              I think you've mixed up some i's and j's in your code in #6. You create local i, which correctly contains j rewritten with a leading zero. But then you never use it anywhere else. So it just sits there. I'm not exactly sure from your description where the name_02, etc. variables are, but wherever they are, you need to refer to them in your code with `i', and not with `j'.

              Comment


              • #8
                Many thanks Nick Cox and Clyde

                Comment

                Working...
                X