2015-04-20 24 views
0

我有一個全球性的宏:在這個宏如何獲得的價值指數在宏觀

global global_macro sheep frog dragon 

我環,我希望能夠基於對global_macro當前索引值,生成三個新變量:

foreach i in $global_macro { 
    ***define local index*** 
      ... 
    gen new_var_`index' = 5 
} 

所以我希望它產生的變量new_var_1new_var_2new_var_3因爲sheepglobal_macro的第一個值,frog是第二,和dragon是第三位。 index將首先包含1,然後2,最後包含3

我知道在擴展宏函數word中基本上有相反的功能。這允許人們根據索引訪問宏中的值 - 而不是根據該值訪問索引。有什麼功能可以做我想做的事嗎?

回答

2

我想這你想要做什麼:

clear 
set more off 

// original list/indices 
local wordlist sheep frog dragon 

// attach indices to words 
quietly forvalues i = 1/3 { 
    local creature : word `i' of `wordlist' 
    local `creature'_idx `i' 
} 

// access indices based on words 
foreach i in frog dragon sheep { 
    display "Creature `i' has index ``i'_idx'" 
} 

大概可以重構,但主要的一點是要爲每個一個local保存其相應的索引;那麼你可以訪問任何單詞的索引(基於單詞)。

(我可能會缺少一些明顯的功能/命令來做你想做的事。)

1

這應該這樣做

local n: word count $global_macro 

forval index = 1/`n' { 
    gen new_var_`index' = 5 
} 

最佳