2009-10-24 54 views
1

我從下面的循環得到奇怪的行爲(只生成遺漏值) - varlist中的名稱{EGEN totalcap x'=total(cap) if unit!=0 & name==" X'」,由STATA foreach循環古怪行爲

的foreach X(年) }

但如果我這樣做只是

EGEN totalcapSOMENAME =總(帽)如果 單元!= 0 & name ==「SOMENAME」,由(年)

然後它計算它應該計算的數字。

這是一個面板數據集,單位表示特定發電機單元(編號爲0的單元爲工廠級觀測值)的動力裝置內的編號。 cap變量是安裝容量。名稱變量標識工廠。解釋爲什麼我需要這個循環很複雜,但問題顯然在於STATA解釋foreach的方式。

回答

1

這裏有幾個問題。最重要的是,你的第一個循環是在整個循環中評估「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如何評估你的循環。

+0

有一件事我忘了突出顯示(但包含在我提供的代碼片段中) - 你不需要循環中x的雙引號,只需單引號......所以應該是=='x ',不是==「x」。 – 2009-10-26 12:30:48