Dear statalists,
I would like to count distinct observations based on certain criteria for previous three years, and save it as a dataset, but it seems I got some problem with my coding. The example below would help to show what I intend to do.
Dataset
I would like to count distinct BNames that shows up in same Loc, Group, Country in the prior three year (as the concept of "number of peers"). For example, in 2004, when Loc==1, Group==2 and Country==Fr, the count would be 1, as both id_6 and id_10 show the same BName, C; but for the same criteria in 2005 the count would be 2, as in id_14 the BName is B, which is different from id_6 and id_10. I have tried the code like this
It turns out to count peers in the same year only, while not count peers in previous years. I'm not sure that is the correct way to use -inrange- command, or I should change the entire code. I would much appreciate if anyone can help or provide any suggestions. Many thanks in advanced!
Kind Regards,
Melanie
I would like to count distinct observations based on certain criteria for previous three years, and save it as a dataset, but it seems I got some problem with my coding. The example below would help to show what I intend to do.
Dataset
Code:
* Example generated by -dataex-. To install: ssc install dataex clear input int Year float(Loc Group) str8 BName long Country float id 2001 1 2 "B" 1 1 2001 1 3 "A" 2 2 2001 1 3 "K" 2 3 2001 2 1 "A" 2 4 2001 2 2 "C" 1 5 2003 1 2 "C" 1 6 2003 1 3 "A" 2 7 2003 2 2 "B" 1 8 2003 2 3 "K" 2 9 2004 1 2 "C" 1 10 2004 1 3 "K" 2 11 2004 2 2 "B" 1 12 2004 2 3 "K" 2 13 2005 1 2 "B" 1 14 2005 1 3 "K" 2 15 2005 2 2 "B" 1 16 end label values Country Country label def Country 1 "Fr", modify label def Country 2 "UK", modify
Code:
bysort Year Loc Group Country: egen sum=nvals(BName) if inrange(Year,Year[_n-2],Year[_n]) bysort Year Loc Group Country: gen _flag=_n keep if _flag==1 keep Year Loc Group Country sum
It turns out to count peers in the same year only, while not count peers in previous years. I'm not sure that is the correct way to use -inrange- command, or I should change the entire code. I would much appreciate if anyone can help or provide any suggestions. Many thanks in advanced!
Kind Regards,
Melanie
Comment