Announcement

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

  • Subdivide an existing group based on another grouping variable

    Dear statalist members,

    I'm trying to reproduce the variable -desired- in the data example below. The variable is a subdivision of the group variable -site- according to -type-, based on the values of grouping variable -dt- within -site-. For example, -desired- subdivides group 2 (ie, type == 2) in site 312 into groups 2 and 3 based on the values of -dt-.

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input long id int site long dt byte(type desired)
    55600 110 71101001 1 1
    55601 110 71101002 2 2
    55602 110 71101002 2 2
    55603 110        . . .
    55604 211 72111004 1 1
    55605 211        . . .
    55606 211        . . .
    55607 312 73121005 2 2
    55608 312 73121006 1 1
    55609 312 73121007 2 3
    55610 312 73121007 2 3
    55611 312        . . .
    end

    I tried:

    Code:
    sort dt type
    egen subgrp= group(site type dt)
    sort id site dt
    list
    but here the numbering in -subgrp- does not restart at each new case of -site-.

    Thank you for your help!

  • #2
    Code:
    by site (type dt), sort: gen wanted = sum((dt != dt[_n-1]) | type != type[_n-1])
    replace wanted = . if missing(type, dt)
    
    assert wanted == desired

    Comment


    • #3
      Thank you Clyde, works perfectly! An online search tells me the square brackets here are referred to as "explicit subscripting", a useful feature I need to become familiar with (more about it at https://www.stata.com/manuals/u13.pdf#u13.7).

      Comment

      Working...
      X