How to do calculation using local macros

38 views Asked by At

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?

2

There are 2 answers

2
SultanOrazbayev On BEST ANSWER

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.

2
Nick Cox On

As @SultanOrazbayev pointed out, you are missing the difference between

local j `i' - 1 

which copies a text string like 2 - 1 to the local macro and

local j = `i' - 1 

which assigns text like 1 to the local macro.

See e.g. https://www.stata.com/manuals/u18.pdf for a basic introduction to local macros.

On the information in the question, the loop should just be rewritten

forvalues j = 1/9 {
    drop if view`j' == 0 
}

noting that == not = is the required syntax.