1

I have a global macro:

global global_macro sheep frog dragon

I loop over this macro and I want to be able to generate three new variables based on the current index value of global_macro:

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

So I want it to produce the variables new_var_1, new_var_2, and new_var_3 because sheep is the first value in global_macro, frog is the second, and dragon is the third. index would first contain 1, then 2, and finally 3.

I know that there is basically the opposite functionality in the extended macro function called word. This allows one to access a value in a macro based on the index - as opposed to accessing the index based on the value.

Is there a function to do what I would like?

bill999
  • 2,147
  • 8
  • 51
  • 103

2 Answers2

2

This should do it

local n: word count $global_macro

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

Best

harre
  • 7,081
  • 2
  • 16
  • 28
2

I think this does what you want:

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'"
}

It can probably be refactored, but the main point is to create for each word a local that holds its corresponding index; then you can access any word's index (based on the word).

(I may be missing some obvious function/command to do what you want.)

Roberto Ferrer
  • 11,024
  • 1
  • 21
  • 23