Search code examples
statastata-macros

How to do calculation using local macros


In Stata I am looping over i and inside the loop, I want to get i-1. This is what I tried:

forvalues i = 2/10{
    local j `i' - 1
    drop if view`j' = 0
}

However, the j is actually 2-1 instead of 1.

If I use display("`j'"), I will get 2-1. So I am not able to do calculations using my local i this way.

Is there any way to get the result of `i' - 1 in the loop?


Solution

  • One way is to use assignment ("=" sign):

    local i 1
    di "`i'"
    local j = `i' + 1
    di "`j'"
    

    Note that the proper terminology is "local macro". The term "variable" is reserved to refer to the variables in the dataset.