user1769925
user1769925

Reputation: 598

Stata: Loop up if observation exists

I have a dataset of the following form:

vars: 
year, firm, executive

data:
2002, initech, steve
2002, microtech, john
2003, initech, mike
2003, microtech, john

I want to add a new variable "sticksaround" that indicates whether a given executive is still with his firm the next year. For my data, I would want the created values to be:

0
1
0 or missing (both fine)
0 or missing (both fine)

Any thoughts on how I would best go about this?

I was thinking about looping over all observations -- but how do I check if there is an entry with the same executive for the next year?

Upvotes: 0

Views: 512

Answers (1)

Brendan
Brendan

Reputation: 4011

Try:

bysort firm (year): gen sticksaround = executive == executive[_n+1]

E.g.:

clear
input  year str15 firm str5 executive
2002 "initech" "steve"
2002 "microtech" "john"
2003 "initech" "mike"
2003 "microtech" "john"
end

bysort firm (year): gen sticksaround = executive == executive[_n+1]

li

Or if you need to compare (e.g.) 2002 to 2003, and not 2002 to 2004 if 2003 is missing, use tsset and try (note that you will need to encode firm and executive):

gen sticksaround = executive == F.executive

See help by and help tsset for more information.

Upvotes: 1

Related Questions