Announcement

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

  • How do I count number of times a variable changes?

    I'm doing a study where I need to figure out how often a certain facility changes its type during the study period (ex. type=0 if small facility, type=1 if big facility) and the facility type changes from year to year. (ex. in 2004 and 2005 they would be type 0, 2006 type 1, 2007 type 0). So in this case, facility A would have a total of 2 type changes during the study period (went from type 0 to type 1 to type 0).

    Could you help me figure this out? I've never used loops before or macros so am at a lost. Here's an example of the data and I'm looking for total_change. Thank you

    ID Facility Year Type total_changes
    1 A 2004 1 3
    2 A 2004 1 3
    3 A 2004 1 3
    4 A 2004 1 3
    5 A 2005 0 3
    6 A 2005 0 3
    7 A 2005 0 3
    8 A 2006 1 3
    9 A 2006 1 3
    10 A 2007 0 3
    11 A 2007 0 3
    12 A 2007 0 3

    14 B 2004 1 0
    15 B 2004 1 0
    16 B 2004 1 0
    17 B 2004 1 0
    18 B 2006 1 0
    19 B 2006 1 0
    20 B 2006 1 0

  • #2
    Your text and your example contradict each other as A changes 3 times, not 2.

    The number wanted is the number of spells minus 1, a spell being a period with constant Facility.

    We subtract 1 because a single spell is no change, two spells one change, etc.

    See http://www.stata-journal.com/sjpdf.h...iclenum=dm0029 for a detailed discussion and tsspell (SSC) for a more general implementation.

    Code:
    input ID str1 Facility Year Type total_changes
    1 A 2004 1 3
    2 A 2004 1 3
    3 A 2004 1 3
    4 A 2004 1 3
    5 A 2005 0 3
    6 A 2005 0 3
    7 A 2005 0 3
    8 A 2006 1 3
    9 A 2006 1 3
    10 A 2007 0 3
    11 A 2007 0 3
    12 A 2007 0 3
    14 B 2004 1 0
    15 B 2004 1 0
    16 B 2004 1 0
    17 B 2004 1 0
    18 B 2006 1 0
    19 B 2006 1 0
    20 B 2006 1 0
    end 
    bysort Facility (Year) : gen nchanges = sum(Type != Type[_n-1]) 
    by Facility : replace nchanges = nchanges[_N] - 1 
    assert nchanges == total_changes
    No loops or macros are needed, except the tacit loop given by by:.

    Comment


    • #3
      Thank you very much for your help!

      Comment

      Working...
      X