Haven't tried why egen with by not working. There are various ways to
approach this. And one of them that does not use egen and by is as follows
(you can use Scott Long's _pecats to get locals: var1lbl and var2lbl :
suppose there are 10 years and 20 countries
preserve
set obs 200 // if obs <200
local var1lbl "all the vavalues of country"
local var2lbl "all the values of year"
local i = 1
foreach var1val in `var1lbl' {
foreach var2val in `var2lbl' {
replace country = `var1val' if _n =`i'
replace year = `var2val' if _n=`i'
count var3
replace cntvar3 = r(N)
}
}
keep if _n<=200
keep country year cntvar3
save whereever