如何获取宏的价值指数

问题描述 投票:0回答:2

我有一个全球宏:

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。这允许人们基于索引访问宏中的值 - 而不是基于值访问索引。

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

indexing global stata stata-macros
2个回答
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
}

最好

© www.soinside.com 2019 - 2024. All rights reserved.