Warm tip: This article is reproduced from stackoverflow.com, please click
stata

Dummy equals 1 if has the same entry as in another row

发布于 2020-04-23 15:44:04

I have a dataset on employment history that looks like below:

Year    PersonID    Company
2010      a            1
2010      b            1
2010      c            2
2010      d            3
2010      e            1
2011      a            2
2011      b            1
2011      c            2
2011      d            3
2011      e            1

I want to create a variable, which equals 1 if the person is in the same company as Person a. Note, Person a could change job over time.

The result looks like:

Year    PersonID    Company     SameAsA
2010      a            1          1
2010      b            1          1
2010      c            2          0
2010      d            3          0
2010      e            1          1
2011      a            2          1
2011      b            1          0
2011      c            2          1
2011      d            3          0
2011      e            1          0

How can I generate the variable "SameAsA"?

Questioner
Tian
Viewed
31
Nick Cox 2020-02-11 18:14

You want an indicator variable for a being in the company at a given time. The approach of @Cybernike can be telescoped like this:

clear
input Year  str3 PersonID   Company
2010    a   1
2010    b   1
2010    c   2
2010    d   3
2010    e   1
2011    a   2
2011    b   1
2011    c   2
2011    d   3
2011    e   1
end

bysort Year Company : egen wanted = max(PersonID == "a") 

list, sepby(Year Company) 

     +------------------------------------+
     | Year   PersonID   Company   wanted |
     |------------------------------------|
  1. | 2010          e         1        1 |
  2. | 2010          a         1        1 |
  3. | 2010          b         1        1 |
     |------------------------------------|
  4. | 2010          c         2        0 |
     |------------------------------------|
  5. | 2010          d         3        0 |
     |------------------------------------|
  6. | 2011          e         1        0 |
  7. | 2011          b         1        0 |
     |------------------------------------|
  8. | 2011          c         2        1 |
  9. | 2011          a         2        1 |
     |------------------------------------|
 10. | 2011          d         3        0 |
     +------------------------------------+

For more discussion, see this FAQ and this tutorial review.