这里有几个问题。最重要的是,你的第一个循环是在整个循环中评估“name”这个词来代替“x”。所以它的运行您-egen-命令:
foreach x of varlist name {
egen totalcapname = total(cap) if unit!=0 and name=="name", by(year)
}
我怀疑这是你真正想要的东西 - 我想你想它由每个项目(观察)在“名称”变量评估,因为你使用的if语句==“x'". So, you need to either get rid of the double quotes around the "
x'”,或者设置一个本地宏,并设置egen循环以评估“name”变量中的每个项目。
我在你的代码中看到的第二个错误是,你错过了循环中“x”的向前或向左引号 - 它应该读为“`x'”,而不是“x”“。
下面是我认为你想运行的一个例子。为了便于说明,我使用Stata内置的“auto.dta”数据集来运行循环& standalone -egen-statement ...请注意,我将auto.dta中的变量重命名为变量的名称:
***********
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)
***********
尝试在Stata do-file中运行此示例。另外,当你遇到这些问题时(循环创建的结果与独立命令不同),总是尝试在上面输入-set trace,这样你就可以看到Stata如何评估你的循环。
有一件事我忘了突出显示(但包含在我提供的代码片段中) - 你不需要循环中x的双引号,只需单引号......所以应该是=='x ',不是==“x”。 – 2009-10-26 12:30:48