1

我有一个全局宏:

global global_macro sheep frog dragon

我循环这个宏,我希望能够根据当前索引值生成三个新变量global_macro

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

所以我希望它产生变量new_var_1,new_var_2new_var_3因为sheep是 中的第一个值global_macro,frog是第二个,dragon是第三个。index将首先包含1,然后2,最后3

我知道扩展宏函数中基本上有相反的功能,称为word. 这允许人们根据索引访问宏中的值 - 而不是根据值访问索引。

有什么功能可以做我想做的事吗?

4

2 回答 2

2

这应该这样做

local n: word count $global_macro

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

最好的

于 2015-04-20T19:06:06.350 回答
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保存其对应索引的 a;然后您可以访问任何单词的索引(基于单词)。

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

于 2015-04-20T20:56:23.053 回答