Announcement

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

  • Setting a dummy if names appear in the previous year!

    Dear All, Suppose that I have data
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(x year) str8 city float change
    1 1999 "A" 0
    1 1999 "B" 0
    1 2000 "C" 0
    1 2000 "A" 1
    1 2001 "D" 0
    1 2001 "E" 0
    2 1999 "X" 0
    2 1999 "W" 0
    2 2000 "W" 1
    2 2000 "X" 1
    2 2001 "Z" 0
    2 2001 "X" 1
    end
    For each `x', I 'd like to define a dummy (`change'). If the `city' names (in the current year) appeared in the previous year (one year before only), then `change'=1, 0 otherwise. Thanks.
    Ho-Chuan (River) Huang
    Stata 19.0, MP(4)

  • #2
    For this data, at least, the following code seems to do what you want.
    Code:
    . bysort x city (year): generate wanted = year[_n-1] == year-1
    
    . sort x year city
    
    . list, sepby(x year) noobs
    
      +-----------------------------------+
      | x   year   city   change   wanted |
      |-----------------------------------|
      | 1   1999      A        0        0 |
      | 1   1999      B        0        0 |
      |-----------------------------------|
      | 1   2000      A        1        1 |
      | 1   2000      C        0        0 |
      |-----------------------------------|
      | 1   2001      D        0        0 |
      | 1   2001      E        0        0 |
      |-----------------------------------|
      | 2   1999      W        0        0 |
      | 2   1999      X        0        0 |
      |-----------------------------------|
      | 2   2000      W        1        1 |
      | 2   2000      X        1        1 |
      |-----------------------------------|
      | 2   2001      X        1        1 |
      | 2   2001      Z        0        0 |
      +-----------------------------------+

    Comment


    • #3
      Dear William, Many thanks for this wonderful solution.
      Ho-Chuan (River) Huang
      Stata 19.0, MP(4)

      Comment

      Working...
      X