Announcement

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

  • Numbering new values of a variable 1 to N

    My data has a country variable using three digit ISO-3166 codes. The underlying codes aren't quite sequential anyway, and then because I'm using a subset of countries there are gaps. To make some loops run smoothly, I would like to have a variable where countries are 1, 2, 3 etc. I think the backbone of the code I need is something like:
    Code:
    //sort country wave id
    // gen newvar=1 if obs==1
    //gen newvar=newvar(_n-1) if country(_n-1)=country
    //replace newvar=newvar(_n-1)+1 if country(_n-1)!=country
    I expect there are obvious pitfalls to that approach that I'm missing, and this feels like something egen should be able to do in a single line. Any guidance appreciated.

  • #2
    Try

    Code:
    egen cntry = group(country)

    Comment


    • #3
      Or alternatively if country identifies an observation

      Code:
      gen cntry = _n
      and if none of those work provide a data sample with -dataex-.

      Comment


      • #4
        The idea is good, and can be coded up (You need == consistently when testing for equality.)


        Code:
        bysort country : gen newvar = 1 if _n == 1 
        replace newvar = sum(newvar)
        or

        Code:
        sort country 
        gen newvar = sum(country != country[_n-1] )
        but it's what

        Code:
        egen newvar = group(country) , label
        does any way. (I added label as good practice going beyond you did.)

        See FAQs

        https://www.stata.com/support/faqs/d...p-identifiers/

        https://www.stata.com/support/faqs/d...-with-foreach/

        The latter FAQ is just a start on an enormous topic. Getting groupwise results doesn't always require loops; see e.g. statsby, runby (SSC), rangestat (SSC).

        It's a fair bet that what you want to do next is covered by hundreds of threads here, so do make it specific.

        Comment


        • #5
          egen group worked perfectly. Thanks!
          Appreciate the pointer to the FAQ too -- no doubt it will save me posting more obvious questions here.
          Last edited by Josephine George; 03 Oct 2020, 04:53.

          Comment

          Working...
          X