2014-12-08 23 views
0

我的數據集中有一個變量countrycode,它使用ISO數字代碼(基本上是3個數字)來標識每個觀察來自哪個國家。但是,要與其他數據集合並,我需要將這些國家代碼更改爲ISO Alpha值(3個字母)。使用本地Stata來更改變量的值

我有一個csv文件(ISOcodes.csv)匹配的數字代碼和alpha代碼;它看起來像這樣:

num,name,alpha 
004,Afghanistan,AFG 
248,Åland Islands,ALA 
008,Albania,ALB 
... 

這是我嘗試的解決方案:

insheet using ISOcodes.csv 

* Create variables ISOnum_1, ISOnum_2, etc. and ISOalpha_1, ISOalpha_2, etc. 
* ISOnum_1 and ISOalpha_1 should refer to the same country 
local N = _N 
forvalues x = 1 (1) `N' { 
    local ISOnum_`x' = num[`x'] 
    local ISOalpha_`x' = num[`x'] 
} 

clear 
insheet using maindataset.csv 

* Replace all numeric values in `countrycode` with the corresponding `alpha` values 
recast countrycode str3 
foreach x = 1 (1) `N' { 
    replace countrycode = ISOalpha_`x' if countrycode == ISOnum_`x' 
} 

list countrycode 

不過,我還沒有能夠創造當地人;當我運行這個時,只要我嘗試分配第一個本地時,就會收到錯誤「num not allowed」。關於這裏出了什麼問題的任何想法?我在下一節中會遇到任何問題?我對Stata非常陌生。

此外,當我清除ISOcodes.csv數據集以導入我的主數據集時,是否會丟失我剛分配的所有本地數據?

+0

交叉發佈在statalist.org/forums/forum/general-stata-discussion/general/...在其他論壇上交叉發佈並非是無序的,但是可以有禮貌地告訴我們。見例如http://meta.stackexchange.com/questions/141823/why-is-cross-posting-wrong-on-an-external-site進行討論。統計專家對此相反明確。 – 2014-12-08 11:36:54

回答

2

你不需要循環。您想要使用merge命令。下例:

clear 

*----- example data sets ----- 

// crosswalk file 

input /// 
str3 numiso str15 name str3 alpha 
004 "afghanistan" "afg" 
248 "aland islands" "ala" 
008 "albania" "alb" 
end 

tempfile crossfile 
save "`crossfile'" 

list 

more 

// main data set 

clear 

input /// 
str3 numiso str15 name gdp 
004 "afghanistan" 476 
248 "aland islands" 644 
008 "albania" 500 
end 

list 

*----- what you want ----- 

merge 1:1 numiso using "`crossfile'" 

list 

您可能需要調整細節,因爲您對數據集描述不確切。見help merge

最近這個問題已經出現:顯式循環在Stata中並不像其他語言那樣普遍,因爲默認情況下,命令會影響所有觀察值(從1到_N)。例如參見Stata counting substring

+0

這太容易了,謝謝! – bsauce 2014-12-08 03:29:13

1

@羅伯託費雷爾正確地解釋說,循環觀測並不是一個好的策略,或者一般在Stata中,並給出了一個替代解決方案。

讓原因不明你的代碼有什麼問題。

奇怪或不奇怪,我看不到什麼會產生您報告的錯誤,但還有其他幾種。

  1. 導入時,在num前導零將獲得剝奪,除非你導入它們明確的字符串變量。 Stata會將012讀爲12.

  2. 首先,您將使用值num創建兩組本地宏。一套應該使用num;另一個應該使用alpha

  3. 實質上,本地宏是而不是變量在Stata中。請參閱this post以瞭解關於此問題和其他常見混淆的討論。

這不僅僅是糾正術語:你的代碼錯誤,因爲你指的是本地宏,就好像它們是變量一樣,這是行不通的。

您正在使用符號來評估本地宏,但必須一直進行。

  • 你需要用雙引號弄清楚您在使用numalpha值時,需要一個字符串評價。

  • 您還混淆了foreachforvalues

  • 你最終環路站作爲在

    foreach x = 1 (1) `N' { 
        replace countrycode = ISOalpha_`x' if countrycode == ISOnum_`x' 
    } 
    

    這應該更像

    forval x = 1(1)`N' { 
        replace countrycode = "`ISOalpha_`x''" if countrycode == "`ISOnum_`x''" 
    } 
    

    UPDATE:在猜測,報告的錯誤出現,因爲實際上你使用完全不同從你說的語法

    在Statalist帳,您報告語法如

    local ISOnum_`x' : num[`x'] 
    

    這確實是非法的。