Search code examples
statastata-macros

Assigning a range of values to a macro


I am trying to rename a list of variables using a for loop.

My code looks like this:

local x 99 00 01 02 03 04 05 06 07 08 09 10 11 12
local k  2 4 6 8 10 12 14 16 18 20 22 24 26 28
local n: word count `x'

forvalues i = 1 / `n' {
    local a : word `i' of `x'
    local b : word `i' of `k'
    rename v`b' num`a'
}

I was wondering whether it is possible to assign the range for the macro k without writing it manually. Note that the delta between two values is not one.


Solution

  • In your case, you just want original suffixes 2(2)28, so doubling 1(1)14 suffices. Otherwise help tokenize.

    local x 99 00 01 02 03 04 05 06 07 08 09 10 11 12
    tokenize "`x'"
    local n: word count `x'
    forvalues i = 1/`n' {
        local I = 2 * `i' 
        rename v`I' num``i'' 
    }
    

    Other arithmetic progressions are as easy. For example, 3(2)... is

        local I = 2 * `i' + 1