Alexander:
You've got a couple of issues here. Most importantly, your first loop is evaluating the word "name" in place of "x" throughout your loop. So its running your -egen- command as:
foreach x of varlist name {
egen totalcapname = total(cap) if unit!=0 and name=="name", by(year)
}
I doubt this is what you really want--I think you want it to evaluate by each item (observation) in your "name" variable since you used the if statement name=="x'". So, you need to either get rid of the double quotes around the "
x'" in your -if- statement OR set up a local macro and set the egen loop to evaluate for each item in your "name" variable.
The second error I see in your code is that you are missing the forward or left quote for the "x" in the loop--it should read "`x'" , not "x'".
Here is an example of what I THINK you want to run. For illustration purposes, I am using the Stata in-built "auto.dta" dataset to run your loop & standalone -egen- statement...please note that I rename the variables in the auto.dta to the names of your variables:
***********
clear
sysuse auto
**
//this section renames the auto.dta variables to the name of your variables//
gen year = [_n]
rename mpg cap
rename price unit
rename make name
**NOTE: your "SOMENAME" will be "Subaru" in this example!**
**
//here's the loop you should be running//
foreach x of varlist name {
egen totalcap`x'=total(cap) if unit!=0 & name==`x', by(year)
}
//without the loop//
egen totalcapSOMENAME=total(cap) if unit!=0 & name=="Subaru", by(year)
//Display the results//
li name unit cap totalcap* if !missing(totalcapSOMENAME)
***********
*
Try running this example in a Stata do-file. Also, when you have these sort of issues (where the loop creates a different outcome than the stand alone command), always try typing -set trace on- so that you can see how Stata is evaluating your loop.
Eric A. Booth | [email protected] | [email protected]